Explain Codes LogoExplain Codes Logo

How do I check if a file exists in Java?

java
file-existence
file-creation
java-nio-2
Nikita BarsukovbyNikita Barsukov·Oct 15, 2024
TLDR

To verify a file's existence in Java quickly, use Files.exists from java.nio.file:

boolean fileExists = Files.exists(Paths.get("/your/file/path.txt"));

The Boolean fileExists will be true if the file exists, and false otherwise. This is a succinct and efficient method highly recommended for Java SE 7 and later versions.

Avoid false positives with directories

Confirming the existence of only a file (not a directory) requires a combination of exists() and !isDirectory():

File f = new File("/your/file/path.txt"); if (f.exists() && !f.isDirectory()) { System.out.println("Houston, we found the file!"); // Print when it's not a directory and it exists }

This ensures our existence check is for a file only – avoiding any confusion with directories.

File creation if non-existent

Creating a file only if it doesn't currently exist can be achieved with exists() and createNewFile():

File f = new File("/your/file/path.txt"); if (!f.exists()) { f.createNewFile(); // Creates new file if it doesn't exist — like a magician pulling a rabbit out of a hat }

This snippet is useful when your logic involves creating a new file from scratch or working on a brand new set of data.

Taking full advantage of Java NIO.2

Introduced in Java 7, NIO.2's Files class offers a clear API:

  • Regular files: Files.isRegularFile(path) ensures the path is a file, not a directory or anything else.
  • Directories: Files.isDirectory(path) checks if a path points to a directory.
  • Uncertainty Principle: Both Files.exists and Files.notExists can return false when determining a file's existence isn't possible.

A simultaneous check for the file's existence and its readability would look like this:

Path path = Paths.get("/your/file/path.txt"); boolean IsFileExistingAndReadable = Files.exists(path) && Files.isReadable(path);

Here, the code ensures the existence and accessibility of a file before performing any actions with it.

The Java 8 way

Java 8 introduced the Files and Paths classes, offering a preferred way to deal with files:

Path path = Paths.get("/your/file/path.txt"); // To just check for its existence boolean exists = Files.exists(path); // To doubly confirm it isn't a directory and exists boolean isFile = Files.isRegularFile(path); // Error-tolerant with symbolic links boolean unsure = Files.exists(path, new LinkOption[]{ LinkOption.NOFOLLOW_LINKS });

In the last example, the code avoids following symbolic links. This is useful when dealing with complex file system structures.

Ensure accuracy of file paths

Ensure that filePathString is a valid path. Invalid paths lead to unexpected behaviour or errors. So, handle cases where the path may be invalid:

try { Path path = Paths.get(filePathString); // Use path here... System.out.println("The file path is valid. Carry on!"); } catch (InvalidPathException ex) { System.out.println("Invalid file path. Please try again with the correct path, you're not typing a secret superpower code!"); }