How do I check if a file exists in Java?

JavaFile IoIoFile Exists

Java Problem Overview


> How can I check whether a file exists, before opening it for reading in Java (the equivalent of Perl's -e $filename)?

The only similar question on SO deals with writing the file and was thus answered using FileWriter which is obviously not applicable here.

If possible I'd prefer a real API call returning true/false as opposed to some "Call API to open a file and catch when it throws an exception which you check for 'no file' in the text", but I can live with the latter.

Java Solutions


Solution 1 - Java

Using java.io.File:

File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) { 
    // do something
}

Solution 2 - Java

I would recommend using isFile() instead of exists(). Most of the time you are looking to check if the path points to a file not only that it exists. Remember that exists() will return true if your path points to a directory.

new File("path/to/file.txt").isFile();

new File("C:/").exists() will return true but will not allow you to open and read from it as a file.

Solution 3 - Java

By using nio in Java SE 7,

import java.nio.file.*;

Path path = Paths.get(filePathString);

if (Files.exists(path)) {
  // file exist
}

if (Files.notExists(path)) {
  // file is not exist
}

If both exists and notExists return false, the existence of the file cannot be verified. (maybe no access right to this path)

You can check if path is a directory or regular file.

if (Files.isDirectory(path)) {
  // path is directory
}

if (Files.isRegularFile(path)) {
  // path is regular file
}

Please check this Java SE 7 tutorial.

Solution 4 - Java

Using Java 8:

if(Files.exists(Paths.get(filePathString))) { 
    // do something
}

Solution 5 - Java

File f = new File(filePathString); 

This will not create a physical file. Will just create an object of the class File. To physically create a file you have to explicitly create it:

f.createNewFile();

So f.exists() can be used to check whether such a file exists or not.

Solution 6 - Java

f.isFile() && f.canRead()

Solution 7 - Java

There are multiple ways to achieve this.

  1. In case of just for existence. It could be file or a directory.

     new File("/path/to/file").exists();
    
  2. Check for file

     File f = new File("/path/to/file"); 
       if(f.exists() && f.isFile()) {}
    
  3. Check for Directory.

    File f = new File("/path/to/file"); if(f.exists() && f.isDirectory()) {}

  4. Java 7 way.

     Path path = Paths.get("/path/to/file");
     Files.exists(path)  // Existence 
     Files.isDirectory(path)  // is Directory
     Files.isRegularFile(path)  // Regular file 
     Files.isSymbolicLink(path)  // Symbolic Link
    

Solution 8 - Java

You can use the following: File.exists()

Solution 9 - Java

first hit for "java file exists" on google:

import java.io.*;

public class FileTest {
    public static void main(String args[]) {
        File f = new File(args[0]);
        System.out.println(f + (f.exists()? " is found " : " is missing "));
    }
}

Solution 10 - Java

Don't. Just catch the FileNotFoundException. The file system has to test whether the file exists anyway. There is no point in doing all that twice, and several reasons not to, such as:

  • double the code
  • the timing window problem whereby the file might exist when you test but not when you open, or vice versa, and
  • the fact that, as the existence of this question shows, you might make the wrong test and get the wrong answer.

Don't try to second-guess the system. It knows. And don't try to predict the future. In general the best way to test whether any resource is available is just to try to use it.

Solution 11 - Java

For me a combination of the accepted answer by Sean A.O. Harney and the resulting comment by Cort3z seems to be the best solution.

Used the following snippet:

File f = new File(filePathString);
if(f.exists() && f.isFile()) {
    //do something ...
}

Hope this could help someone.

Solution 12 - Java

I know I'm a bit late in this thread. However, here is my answer, valid since Java 7 and up.

The following snippet

if(Files.isRegularFile(Paths.get(pathToFile))) {
    // do something
}

is perfectly satifactory, because method isRegularFile returns false if file does not exist. Therefore, no need to check if Files.exists(...).

Note that other parameters are options indicating how links should be handled. By default, symbolic links are followed.

From Java Oracle documentation

Solution 13 - Java

It's also well worth getting familiar with Commons FileUtils https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FileUtils.html This has additional methods for managing files and often better than JDK.

Solution 14 - Java

Simple example with good coding practices and covering all cases :

 private static void fetchIndexSafely(String url) throws FileAlreadyExistsException {
        File f = new File(Constants.RFC_INDEX_LOCAL_NAME);
        if (f.exists()) {
            throw new FileAlreadyExistsException(f.getAbsolutePath());
        } else {
            try {
                URL u = new URL(url);
                FileUtils.copyURLToFile(u, f);
            } catch (MalformedURLException ex) {
                Logger.getLogger(RfcFetcher.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(RfcFetcher.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

Reference and more examples at

https://zgrepcode.com/examples/java/java/nio/file/filealreadyexistsexception-implementations

Solution 15 - Java

Don't use File constructor with String.
This may not work!
Instead of this use URI:

File f = new File(new URI("file:///"+filePathString.replace('\\', '/')));
if(f.exists() && !f.isDirectory()) { 
    // to do
}

Solution 16 - Java

You can make it this way

import java.nio.file.Paths;

String file = "myfile.sss";
if(Paths.get(file).toFile().isFile()){
    //...do somethinh
}

Solution 17 - Java

There is specific purpose to design these methods. We can't say use anyone to check file exist or not.

  1. isFile(): Tests whether the file denoted by this abstract pathname is a normal file.
  2. exists(): Tests whether the file or directory denoted by this abstract pathname exists. docs.oracle.com

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDVKView Question on Stackoverflow
Solution 1 - JavaSean A.O. HarneyView Answer on Stackoverflow
Solution 2 - JavaChris DailView Answer on Stackoverflow
Solution 3 - JavaWonilView Answer on Stackoverflow
Solution 4 - JavaWendelView Answer on Stackoverflow
Solution 5 - JavarizwanView Answer on Stackoverflow
Solution 6 - JavajhumbleView Answer on Stackoverflow
Solution 7 - JavaRaghu K NairView Answer on Stackoverflow
Solution 8 - JavaFrancis Upton IVView Answer on Stackoverflow
Solution 9 - Javajust somebodyView Answer on Stackoverflow
Solution 10 - Javauser207421View Answer on Stackoverflow
Solution 11 - JavaX-FateView Answer on Stackoverflow
Solution 12 - Javaavi.elkharratView Answer on Stackoverflow
Solution 13 - Javapeter.murray.rustView Answer on Stackoverflow
Solution 14 - JavaAmandeep SinghView Answer on Stackoverflow
Solution 15 - JavaiviorelView Answer on Stackoverflow
Solution 16 - JavaRodrigo PavanView Answer on Stackoverflow
Solution 17 - JavaAtul JainView Answer on Stackoverflow