Saturday, October 25, 2025
HomeLanguagesJavaHow to Check a File or Directory Exists in Java?

How to Check a File or Directory Exists in Java?

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
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS