In this quick and short article, you’ll find two examples demonstrating how to check if a File or Directory exists at a given path in Java.
We’re going to get familiar with different ways to check the existence of a file or directory.
Check if a File/Directory exists using Java IO’s File.exists()
import java.io.File;
public class CheckFileExists1 {
public static void main(String[] args) {
File file = new File("/Users/callicoder/demo.txt");
if(file.exists()) {
System.out.printf("File %s exists%n", file);
} else {
System.out.printf("File %s doesn't exist%n", file);
}
}
}
Check if a File/Directory exists using Java NIO’s Files.exists() or Files.notExists()
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CheckFileExists {
public static void main(String[] args) {
Path filePath = Paths.get("/Users/callicoder/demo.txt");
// Checking existence using Files.exists
if(Files.exists(filePath)) {
System.out.printf("File %s exists%n", filePath);
} else {
System.out.printf("File %s doesn't exist%n", filePath);
}
// Checking existence using Files.notExists
if(Files.notExists(filePath)) {
System.out.printf("File %s doesn't exist%n", filePath);
} else {
System.out.printf("File %s exists%n", filePath);
}
}
}