How to Check if a File Exists in Java?
Last Updated :
02 Feb, 2024
In Java programming, working with files is now a more common task. Developing a code to manage file automatization using Java. In this article, we will discuss how to check if a file exists in Java. By using the java.io.File class we will discuss two methods to check if a file exists or not.
Approaches to check if a file exists in Java
We have two ways to get the list of all the files in a directory in Java.
- Using exists() method in java.io.File
- Using java.nio.file Package
Java Program to Check If a File Exists
Below are the implementations of the two approaches using the Java programming language.
1. Using exists() Method in java.io.File class
This is the old way to check if a file exists by using the exists() method in the java.io.File class. Now, let us understand this with the help of an example:
Java
import java.io.File;
public class FileExistenceExample {
public static void main(String[] args) {
String filePath = "C:\Users\GFG0354\Documents\JavaCode" ;
File file = new File(filePath);
if (file.exists()) {
System.out.println( "File Exists" );
} else {
System.out.println( "File does not Exist." );
}
}
}
|
Output in Console:
Explanation of the above Program:
- In the above example, it checks if a file exists at a specified path. It uses the
File
class to represent the file and checks its existence with the exists()
method.
- If the file exists, it prints “File Exists”; otherwise, it prints “File does not Exist.”
2. Using java.nio.file Package
This is the new way to check which was introduced in Java New I/O in Java 7. The java.nio.file.Files class provides a method called exists(). Now, let us understand this with the help of an example:
Java
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
public class FileExistenceNIOExample {
public static void main(String[] args) {
String filePath = "C:\\Users\\GFG0354\\Documents\\JavaCode" ;
Path path = FileSystems.getDefault().getPath(filePath);
if (Files.exists(path)) {
System.out.println( "File Exists" );
} else {
System.out.println( "File does not Exist" );
}
}
}
|
Output in Console:
Explanation of the above Program:
- In the above example, it uses the NIO (New I/O) package to check the existence of a file at a specified path.
- It employs the
FileSystems
and Files
classes to create a Path
object for the file and verify its existence with the Files.exists()
method.
- If the file exists, it prints “File Exist”; otherwise, it prints “File does not Exist.”
Share your thoughts in the comments
Please Login to comment...