How to Check If a File Exists in Java

Published Sep 4, 2022

Let’s see how we can check if a file exists in Java.

1. Using File::isFile

We can use File::isFile to check if a file exists.

boolean doesFileExist(String filePath) {
  File file = new File(filePath.trim());
  return file.isFile();

Using isFile() is equivalent to checking if a file exists and is not a directory: file.exists() && !file.isDirectory().

2. Using Files::isRegularFile (NIO)

We can also use Files::isRegularFile to check for file existence.

boolean doesFileExist(String filePath) {
  Path path = Paths.get(filePath.trim())
  return Files.isRegularFile(path);