Java File Class

A stream in Java is a carrier of data. Nearly 30 stream classes exist in java.io package. Also there are three non-stream classes in java.io package – File, InputStreamReader and OutputStreamWriter. Last two are used as bridges or converters or adapters between low-level byte streams (supported by OS like in, out and err) and character streams.

File class is used to retrieve metadata of a file like the size and permissions for read and write etc.

Following is the class signature of Java File class as defined in java.io package.

public class File extends Object implements Serializable, Comparable

Example on Java File Class – Retrieving meta data of a file.
import java.io.*;
public class RetrieveFileData   
{
  public static void main(String args[ ] ) throws IOException 
  {                                                           		
    File f1 = new File("abc.txt"); 
    
    System.out.println("getName(): " + f1.getName());		
    System.out.println("getAbsolutePath(): " + f1.getAbsolutePath()) ;		
    System.out.println("canRead(): " + f1.canRead()) ;
    System.out.println("canWrite(): " + f1.canWrite()) ;
    System.out.println("isFile(): " + f1.isFile()) ;		
    System.out.println("isDirectory: " + f1.isDirectory()) ;		
    System.out.println("File last modified date: " + f1.lastModified()); 
    System.out.println("File size in bytes: " + f1.length());       
    System.out.println("File exists(): " + f1.exists());		
  }   
}

ss
Output screenshot of Java File Class

All methods are self-explanatory. getAbsolutePath() returns the class path of abc.txt file. lastModified() returns the file creation date or latest modified date. length() returns the size of the file in bytes.

Read more on File class – Changing File Properties

Leave a Comment

Your email address will not be published.