Open In App

Java File Class

Last Updated : 28 Aug, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The File class in Java represents the path of a file or directory. It is used to create, delete and get information about files and directories, but not to read or write their contents. It acts as an abstract representation of file and directory names in the system.

Key Features

  • The File class represents files and directory pathnames in an abstract way.
  • A pathname can be absolute or relative, the parent can be retrieved using getParent().
  • A File object is created by passing a file or directory name to its constructor.
  • File systems may impose access permissions (read, write, execute).
  • File objects are immutable. Once created, their pathname cannot change.

How to Create a File Object 

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

File a = new File("/user/local/bin/geeks");

This defines an abstract file name for the geeks file in the directory /user/local/bin. This is an absolute abstract file name.

Example 1: Program to check if a file or directory physically exists or not.

Java
import java.io.File;

// Displaying file property
class CheckFileExist 
{
    public static void main(String[] args)
    {

        // Accept file name or directory name through command line args
        String fname = args[0];

        // pass the filename or directory name to File object
        File f = new File(fname);

        // apply File class methods on File object
        System.out.println("File name :" + f.getName());
        System.out.println("Path: " + f.getPath());
        System.out.println("Absolute path:" + f.getAbsolutePath());
        System.out.println("Parent:" + f.getParent());
        System.out.println("Exists :" + f.exists());

        if (f.exists()) {
            System.out.println("Is writable:" + f.canWrite());
            System.out.println("Is readable" + f.canRead());
            System.out.println("Is a directory:" + f.isDirectory());
            System.out.println("File Size in bytes " + f.length());
        }
    }
}

Output:

CheckFile
Output

Example 2: Program to display all the contents of a directory.

Here we will accept a directory name from the keyboard and then display all the contents of the directory. For this purpose, list() method can be used as: 

String arr[]=f.list();

This method stores all entries of the directory in the array arr[]. Each element arr[i] can then be passed to a File object to check whether it is a file or a directory.

Java
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

class AllDir 
{
    public static void main(String[] args)
        throws IOException
    {
        // Enter the path and dirname
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        System.out.print("Enter directory path : ");
        String dirpath = br.readLine();
      
        System.out.print("Enter the directory name : ");
        String dname = br.readLine();

        // Create File object with dirpath and dname
        File f = new File(dirpath, dname);

        // If directory exists,then
        if (f.exists()) {
            
          	// Get the contents into arr[], now arr[i] represent either a File or Directory
            String arr[] = f.list();

            // Find no. of entries in the directory
            int n = arr.length;

            // Displaying the entries
            for (int i = 0; i < n; i++) {

                System.out.print(arr[i] + " ");

                // Create File object with the entry and test if it is a file or directory
                File f1 = new File(f,arr[i]);

                if (f1.isFile())
                    System.out.println(": is a file");
                if (f1.isDirectory())
                    System.out.println(": is a directory");
            }

            System.out.println("\nNo of entries in this directory : " + n);
        }
        else
            System.out.println("Directory not found");
    }
}

Output:

All_Directories
Output

Fields in File Class

Field

Type

Description

pathSeparatorStringthe character or string used to separate individual paths in a list of file system paths.
pathSeparatorCharCharthe character used to separate individual paths in a list of file system paths.
separatorStringdefault name separator character represented as a string.
separatorCharChardefault name separator character.

Constructors of Java File Class

  • File(File parent, String child): Creates a new File instance from a parent abstract pathname and a child pathname string.
  • File(String pathname): Creates a new File instance by converting the given pathname string into an abstract pathname.
  • File(String parent, String child): Creates a new File instance from a parent pathname string and a child pathname string.
  • File(URI uri): Creates a new File instance by converting the given file: URI into an abstract pathname.

Methodsof File Class in Java

MethodDescriptionReturn Type
canExecute()Checks if the file is executableboolean
canRead()Checks if the file is readableboolean
canWrite()Checks if the file is writableboolean
compareTo(File other)Lexicographically compares pathnamesint
createNewFile()Atomically creates a new empty fileboolean
createTempFile(String prefix, String suffix)Creates a temp file in default temp directoryFile
delete()Deletes this file or directoryboolean
exists()Checks if the file/directory existsboolean
equals(Object obj)Compares pathnames for equalityboolean
getAbsolutePath()Returns absolute pathname as a stringString
getCanonicalPath()Returns canonical (distinct) pathnameString
getName()Returns name of file or directoryString
getParent()Returns parent pathname stringString
getParentFile()Returns parent as a File objectFile
getPath()Returns the original pathname stringString
getFreeSpace()Returns unallocated bytes in partitionlong
length()Returns file size in byteslong
isDirectory()Checks if it’s a directoryboolean
isFile()Checks if it’s a normal fileboolean
isHidden()Checks if file is hiddenboolean
lastModified()Returns last modification time (ms since epoch)long
list()Returns names of all entries in directoryString[]
listFiles()Returns File objects for entries in directoryFile[]
listFiles(FileFilter filter)Filters entries via FileFilterFile[] 
listFiles(FilenameFilter filter)Filters entries via FilenameFilterFile[]
mkdir()Creates a directoryboolean
mkdirs()Creates directory including parent dirsboolean
renameTo(File dest)Renames or moves file/directoryboolean
setReadOnly()Marks file/directory as read-onlyboolean
setExecutable(boolean exec)Sets owner's execute permissionboolean
setReadable(boolean read)Sets owner's read permissionboolean
setReadable(boolean read, boolean ownerOnly)Sets read permission for owner or allboolean
setWritable(boolean write)Sets owner's write permissionboolean
toURI()Converts pathname to a URI objectURI
toPath()Converts this File to Path (NIO compatibility)Path 
toString()Returns pathname stringString