How to check if a file or folder exists in Java

In Java, we can use Files.exists(pathToFileOrDirectory) to test if a file or a folder exists.

Syntax

Files.exists(pathToFileOrDirectory)

This method returns true if the file is present; otherwise, it returns false. If the file is a symbolic linka file which is a link to another target file, this method returns true only if the target file is present. Otherwise, it returns false.

Main.java
test.txt
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
class Main {
public static void checkFilePresent(Path path){
if (Files.exists(path)) {
if (Files.isDirectory(path)) {
System.out.println("It is a directory");
} else if (Files.isRegularFile(path)) {
System.out.println("File test.txt present");
}
} else {
System.out.println("File not found ");
}
}
public static void main( String args[] ) {
String currentDir = "./";
String fileName1 = "test.txt";
Path path = Paths.get(currentDir + fileName1);
checkFilePresent(path);
String fileName2 = "write.txt";
path = Paths.get(currentDir + fileName2);
checkFilePresent(path);
}
}

In the code above, we have:

  • Created a test.txt file in current directory.

  • Used Files.exist to check if a file exists.

  • If the file was found, we checked if it is a regular file or directory.

  • If the file was not found, we printed File not found.


The File, Path, and Paths classes are present in the java.nio.file package.