Java — How to check if a File or Directory exists | Code Factory

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);
}
}
}
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);
}
}
}
File test.txt exists
File test.txt exists

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store