Monday, January 26, 2026
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
32475 POSTS0 COMMENTS
Milvus
122 POSTS0 COMMENTS
Nango Kala
6847 POSTS0 COMMENTS
Nicole Veronica
11978 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12065 POSTS0 COMMENTS
Shaida Kate Naidoo
6986 POSTS0 COMMENTS
Ted Musemwa
7221 POSTS0 COMMENTS
Thapelo Manthata
6934 POSTS0 COMMENTS
Umr Jansen
6912 POSTS0 COMMENTS