Check If a File or Directory Exists in Java

Learn to test if a file or a directory exists in a given path using Java standard IO and NIO APIs.

1. Using Files.exists() and Files.notExists()

Java NIO provides a few good ways to test whether the specified file or directory exists or not. Use Files.exists() method or Files.notExists() method for such validations.

Path path = Files.createTempFile("testFile", ".txt");
boolean exists = Files.exists(path);     //true

//OR

Path tempDirectory = Files.createTempDirectory("temp-dir");
boolean exists = Files.notExists(tempDirectory);  //false

By default, this method follows the symbolic links. Use the LinkOption#NOFOLLOW_LINKS if symbolic links are not to be followed.

Files.exists(symbolicLinkToFile, LinkOption.NOFOLLOW_LINKS)

2. Using Legacy File.exists()

To test to see if a file or directory exists, use the “exists()” method of the Java java.io.File class.

  • If the exists() method returns true then the file or directory does exist and otherwise does not exists.
  • If there is a read permission issue then it will throw SecurityException.
File tempFile = new File("c:/temp/temp.txt");

boolean exists = tempFile.exists();

3. Checking if File is Readable, Writable or Executable

To verify that the program can access a file as needed, you can use the isReadable(Path), isWritable(Path), and isExecutable(Path) methods.

Java program to test a file if it is readable, writable and executable. You can need to build Path instances as discussed in the linked post.

final Path path = ...;

Files.isReadable(path);

//OR

Files.isWritable(path);

//OR

Files.isExecutable(path);

That’s all for a quick tip related to checking if a file or directory exists or does not exists in java. Along with testing if the program is allowed to append content to it by checking its writable attribute.

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode