How to check if file exists in Java
Java provides extensive support to File Handling. In other words, File handling in Java implies reading from and writing data to a file. The File class from the java.io package, allows us to work with different formats of files. But, before operating on file, we need to check if a file exists or not. There are three possibilities for the file either file exist, or file doesn’t exist or it may be possible that file status is not known.
In Java, there are three different ways to check if a file exists or not. They are as listed below.
- Using exists method of Legacy I/O File class
- Using isFile method of File class
- Using exists method of NIO File class
Method-1: Using exists method of File class
Prior to the Java SE 7 release, the java.io.File
class was the mechanism used for file I/O, but it had several drawbacks. The exists()
is a static method of java.io.File
class that tests whether a file exist or not. This is a traditional approach to find if the file exists or not. This method does not accept any parameter. However, it returns a boolean value True or False to indicate if the file exist or not. Moreover, this method will raise a Security Exception if the file does not have a write access.
There is one more issue with only using the exists()
method to check if a file exists or not. Because, it returns a true value if we accidentally specify a directory. So we have to use the method isDirectory()
also to make sure that the given argument is a file but not a directory.
The syntax of exists method is as shown below.
fileobject.exists()
Example : In this example, we will create two objects of file class that points to the file in the local directory. Here, we are using exists method of legacy file I/O class and is directory method to check if the given file is a directory or not.
// Importing File package
import java.io.File;
public class Main {
public static void main(String[] args) {
// Initializing string to store the path
String s1 = "C:\\sample.txt";
String s2 = "C:\\xyz.txt";
// Creating file handle
File f1 = new File(s1);
File f2 = new File(s2);
// Check if file a exists and is not directory
if (f1.exists() & amp; & amp; !f1.isDirectory()) {
System.out.println(f1 + " exists in the given directory.");
} else {
System.out.println(f1 + " does not exists or it may be a directory.");
}
// Check if a file exists
if (f2.exists()) {
System.out.println(f2 + " exists in the given directory.");
} else {
System.out.println(f2 + " does not exists in the given directory.");
}
}
}
Output:
C:\sample.txt does not exists or it may be a directory.
C:\xyz.txt exists
Method-2: Using isFile method of File class
Prior to the Java SE 7 release, the isFile()
is a static method of java.io.File
class that tests whether a file exist or not. This is a also widely used approach to find if the file exists or not. This method does not accept any parameter. However, it returns a boolean value True or False to indicate if the file exist or not. Moreover, this method will raise a Security Exception if the file does not have a write access.
The advantage of using the isFile()
method over the exists()
method is that we will not have to check if the given file is a directory or not. Unlike, exists()
method this file will not return True for directory.
The syntax of isFile method is as shown below.
fileobject.isFile()
Example :
// Importing File package
import java.io.File;
class Main {
public static void main(String[] args) {
// Storing path as a string
String p = "C:\pythondemo\test.txt";
//Creating file object
File f = new File(p);
// Check if it is a file using isFile method
if (f.isFile()) {
System.out.println("The file " + p + " exists in the given directory.");
} else {
System.out.println("Either file " + p + " doesn't exist in the given directory or this program may not have access to the file");
}
}
}
Output:
Either file C:\pythondemo\test.txt doesn't exist in the given directory or this program may not have access to the file.
Method-3: Using NIO
From Java 7 onward, the exists()
method of java.nio.file.Files is a static method that returns true if the file exists. Whereas, the notExists()
method returns true when it does not exist. Moreover, if both exists()
and notExists()
return false
, the existence of the file cannot be verified. This may happen when the program does not have access to the file. Also the result of this method is immediately outdated. So, if this method indicates the file exists then there is no guarantee that a sub sequence access will succeed. Thus, we must be careful when using this method in security sensitive applications.
Note that Files.exists()
returns true when your path points to a directory. So, it is recommended to use this method along with the Files.isDirectory()
method, which checks the file for a directory.
The syntax of exists method and notExists method is as shown below.
Files.exists(path, options)
Files.notExists(path, options)
The options parameter may be used to indicate how symbolic links are handled for the case that the file is a symbolic link. By default, symbolic links are followed. If the option NOFOLLOW_LINKS is present then symbolic links are not followed.
Example : In this example, we are using get method to obtain a Path to the intended file or directory. Then we can pass that Path to the Files.exists()
method.
// Importing File package
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) {
Path p = Paths.get("/sample.txt");
// check if a file exists for file and directory
if (Files.exists(p)) {
// Check if it is a file
if (Files.isRegularFile(p)) {
System.out.println("File " + p + " exists in this directory!");
}
// Check if it is a directory
if (Files.isDirectory(p)) {
System.out.println("File " + p + " exists in this directory but, it is not a file. It is a directory.");
}
} else {
System.out.println("File " + p + " does not exist in this directory");
}
if (Files.notExists(q)) {
System.out.println("File " + q + " does not exist in this directory");
}
}
}
Output:
File /sample.txt exists in this directory.
File /xyz.txt does not exists in this directory.
Summary
The concept to check if a file exists or not is very useful. In many applications we need to perform some important operations that should not result into exception. So, it is very necessary to check if a file exists or not before proceeding with any other operations. We have covered three different ways to check if a file exists or not in Java with example. All in all, this tutorial, covers everything that you need to know in order to check the existence of file in Java.
References