In this tutorial, we will learn how to check if a file exists or a directory exists at a given path in Java.
1. Java Check if file exists with File.exists() method
To check if a file or directory exists, use the exists() method of the java.io.File class, as shown below:
File file = new File("c:/sample.txt");
boolean exists = file.exists()
If above method returns true
then file or directory exist otherwise it does not exist. Below code shows how to use File.exists() method
package com.kodehelp.javaio;
import java.io.File;
import java.io.FileNotFoundException;
/**
* Created by https://kodehelp.com Date: 3/18/12
*/
public class CheckIfFileExists {
public static void main(String[] args) throws Exception {
File file = new File("c:/sample.txt");
System.out.println("File = " + file.getAbsolutePath());
if (!file.exists()) {
System.out.println("Sample.txt file does not exist!!!");
throw new FileNotFoundException("Sample.txt file does not exist!!!");
} else {
System.out.println("Sample.txt file exist!!!");
}
}
}
2. Files.exists() and Files.notExists() methods
Java NIO also provides good ways to test whether a file exists or not. Use Files.exists()
method or Files.notExists()
method for this.
package com.kodehelp.java.io;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class CheckFileExists {
public static void main(String[] args) {
try {
final Path path = Files.createTempFile("Sample", ".txt");
boolean exists = Files.exists(path); //true
System.out.println(exists);
boolean notExists = Files.notExists(path); //false
System.out.println(notExists);
} catch (IOException e) {
e.printStackTrace();
}
}
}