Skip to content
Related Articles
Open in App
Not now

Related Articles

How to Check a File or Directory Exists in Java?

Improve Article
Save Article
  • Last Updated : 12 Dec, 2022
Improve Article
Save Article

One of the most frequent tasks carried out by a file system in an operating system is checking the existence of a directory or a file. In the form of library functions, most programming languages provide some level of file system accessibility. You will discover how to test an existing file or directory in Java in this post.

Checking/Testing the presence of a directory

The java.io.File class provides useful methods on file. This example shows how to check a file’s existence by using the file.exists() method of File class.

 

Java




// Importing required libraries
import java.io.*;
 
public class GFG {
    public static void main(String[] args)
        throws IOException
    {
        // Creating object of file and providing it path
        File f = new File("C:\\Test\\GFG.txt");
        // Check if the specified file
        // Exists or not
        if (f.exists())
            System.out.println("Exists");
        else
            System.out.println("Does not Exists");
    }
}


Output:

The above code sample will produce the following result (if the file “java.txt” exists in ‘C:/Test’ drive).

Exists
My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!