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 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.txtfile in current directory. -
Used
Files.existto 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, andPathsclasses are present in thejava.nio.filepackage.