Java — How to check if a File or Directory exists | Code Factory
1 min readJul 20, 2020
Donate : Link
WordPress Blog : Link
You’ll find two examples demonstrating how to check if a File or Directory exists at a given path in Java.
Check if a File/Directory exists using Java IO’s File.exists()
package com.example.java.programming.file;import java.io.File;/**
* @author code.factory
*
*/
public class CheckFileExists {
public static void main(String args[]) {
File file = new File("test.txt"); if (file.exists()) {
System.out.printf("File %s exists%n", file);
} else {
System.out.printf("File %s doesn't exist%n", file);
}
}
}
Output :
File test.txt exists
Check if a File/Directory exists using Java NIO’s Files.exists() or Files.notExists()
package com.example.java.programming.file;import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;/**
* @author code.factory
*
*/
public class CheckFileExists {
public static void main(String args[]) {
Path filePath = Paths.get("test.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);
}
}
}
Output :
File test.txt exists
File test.txt exists