In Java, we can use Files.exists(pathToFileOrDirectory)
to test if a file or a folder exists.
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
.
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
, andPaths
classes are present in thejava.nio.file
package.