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

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Bepro Network AMA

Things I wish I knew when I started Flutter

Accessibility. A new hope…

✍🏻 Research for industry use cases of Openshift, how it works.

Getting started with SQL commands

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
Code Factory

Code Factory

More from Medium

Find All Articulation Points in a Graph Using DFS

Exception handling In Java.

Method Overloading and Method Overriding in Java

Different calling forms of REST services with Feign client in Spring Cloud