How to Check a File or Directory Exists in Java?
Last Updated :
12 Dec, 2022
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
import java.io.*;
public class GFG {
public static void main(String[] args)
throws IOException
{
File f = new File( "C:\\Test\\GFG.txt" );
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
Share your thoughts in the comments
Please Login to comment...