Latest Code Tutorials

Java File Class Tutorial | File Class in Java Example


Java File class represents the path of directories and files. It provides the methods for renaming, deleting, and obtaining the properties of a file or directory. The File class is the wrapper class for the file name and its directory path.

Java File Class

The File class is Java’s representation of the file or directory pathname. Because file and directory names have different formats on different platforms, a simple string is not adequate to name them. A File class contains several methods for working with the pathname, deleting and renaming files, creating new directories, listing the contents of an index, and determining several common attributes of files and directories.

  1. It is an abstract representation of file and directory pathnames.
  2. The pathname, whether abstract or in the string form can be either absolute or relative. The parent of the abstract pathname may be obtained by invoking a getParent() method of this class.
  3. First of all, we should create a File class object by passing a filename or directory name to it. The file system may implement restrictions to certain operations on the actual file-system object, such as the reading, writing, and executing. These restrictions are collectively known as access permissions.
  4. Instances of a File class are immutable; that is, once created, the abstract pathname represented by the File object will never change.

The pathname can be absolute or relative.

#Absolute name

It contains the full path and drives letter, i.e., it is the full name of the path.

For example, C:\Documents\TextFiles\sample.txt

#Relative name

It is the file name/path concerning the current working directory.

For example, TextFiles\sample.txt (C:\Documents being the current working directory)

See the following image.

Java File Class

#How to create a File Object in Java

A File object is created by passing in a string that represents the name of a file, or a String or another File object. For example,

File f = new File("/usr/local/bin/hello");

It defines an abstract file name for the hello file in directory /usr/local/bin. This is an absolute abstract file name.

#Creating objects for files and directories

The File class objects can be created by passing the file name or directory name in the string format.

  1. new File(“C:\\Documents\\TextFiles\\sample.txt”) – This creates the object for the file sample.txt
  2. new File(“C:\\Documents”) – This creates the File object for the directory C:\Documents

The File class does not provide the methods for reading and writing the file contents. Instances of the File class are immutable, which means the path names represented cannot be changed once created.

#Constructors of File Class

#File(String pathname)

It creates a File object for the specified pathname for a file or directory.

#File(File parentpath, String childpath)

It creates a File object from an existing file object with its child file/directories pathname.

#File(String parentpath, String childpath)

It creates a File object with the specified parent directory’s pathname and child file/directory pathname.

#File(URI uri)

It creates a File object from a Uniform Resource Identifier.

#Methods of File Class

boolean isFile():

Returns true if the object represents the path of a file.

boolean isDirectory(): 

Returns true if the object represents the path of a directory.

boolean isHidden()

Returns true if a file or directory is hidden.

boolean exists():

Returns true if such a file/ directory exists.

boolean canRead():

Returns true if the read permission of the file is on.

boolean canWrite():

Returns true if the write permission of the file is on.

boolean canExecute():

Tells whether the file is executable or not.

String getName():

Returns the name of the file or directory.

String getPath():

Returns the formatted string path of the file or directory.

String getAbsolutePath():

It returns the absolute path of the file/directory.

long lastModified():

Returns the date when the file was last modified (in milliseconds), this value can be converted into dd-MM-yyyy HH:mm:sss format using SimpleDateFormat class.

long length():

It will give the length of the file.

boolean delete():

Deletes the file or directory.

boolean renameTo(File f):

Renames the file with the given abstract pathname.

File [] listFiles():

Returns the array of File objects of all files contained in the directory specified.

int compareTo(File pathname):

It compares the pathnames of two files.

boolean createNewFile(): 

It creates a new and empty file having the pathname specified in the constructor.

boolean equals(Object obj):

Tests whether the specified abstract pathname and the object are equal or not.

long getFreeSpace():

It returns the number of unallocated bytes, i.e. the free space in the specified partition.

String getParent(): 

It returns the parent directory pathname (string formatted) of the specified file/directory.

File getParentFile(): 

It creates the File object of the parent directory of the specified file/directory.

String[] list():

Returns the array of strings containing the name of the files and directories in the specified directory.

boolean mkdir(): 

Creates the new directory with the specified pathname.

boolean setExecutable(boolean exe): 

Changes the permission of the file to executable and set it true for the owner.

boolean setReadable(boolean read): 

Changes the read permission of the file and set it true for owner.

boolean setReadable(boolean read, boolean own):

Sets the read permission for either owner or everyone.

boolean setReadOnly():

Sets only the read permissions, disabling all other operations.

String toString():

Returns the formatted string path of the abstract pathname of the specified file/directory.

boolean setWritable(boolean canWriteIt):

Sets the write permission for the owner.

URI toURI():

It will return a file URI representing the file/directory abstract pathname.

The following program checks whether a file exists or not, whether it is a file or a directory and also checks all the permissions the file has.


class Example1
  public static void main(String [] args)
    File sample=new File("Demofile.txt");

      System.out.println("The file: 'Demofile.txt' exists.");

      //checking whether it is a file or directory
      System.out.print("Is it a file or directory: ");
        System.out.println("It is a file.");
      else if(sample.isDirectory()==true)
        System.out.println("It is a directory.");

      //checking different kinds of permissions
      System.out.println("The file is readable: " + sample.canRead());
      System.out.println("The file is writable: " + sample.canWrite());
      System.out.println("The file is executable: " + sample.canExecute());
      System.out.println("The file: 'Demofile.txt' does not exist");

See the output.

Methods of File Class in Java

Here’s another program as an example.

The following program lists all the files and directories in a certain directory along with the length of the file and whether it is a file or directory.

class Example2
  public static void main(String [] args)
    //creating the File object for directory Books
    File dir=new File("Books");
        System.out.println("The given is a file");
        System.out.println("The given is a directory");
        //creating an array of File objects for files and directories in the given directory
        File[] listOfFiles=dir.listFiles();

        //traversing the array of files
        for(int i=0;i<listOfFiles.length;i++)
          String fileOrDir="";
          //checking if it is file or directory
          else if(listOfFiles[i].isDirectory())

          //finding the size of the file
          long len=listOfFiles[i].length();
          System.out.println("name: "+listOfFiles[i].getName()+"\nfile or directory: "+fileOrDir+"\nsize (bytes): "+len+"\n");

See the following output.

Constructors of File Class

The following program creates a new file that does not exist in memory and setting the readable permission of the file.


class Example3
  public static void main(String [] args)
    File sample=new File("Demofile3.txt");

    //checking if the file exists
      System.out.println("THE FILE ALREADY EXISTS.");
      System.out.println("THE FILE DOES NOT EXIST.");

      //creating the non existing file
      System.out.println("creating new file...");
        System.out.println("File created...");
      catch(Exception e)

      //set only readable permission

      //checking all permission
      System.out.println("Permissions of the file:");
      System.out.println("The file is readable: " + sample.canRead());
      System.out.println("The file is writable: " + sample.canWrite());


See the following output. File Class in Java Example

Finally, Java File Class Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.