How do I check if a file exists in Java?

1,289,380

Solution 1

Using java.io.File:

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

Solution 2

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

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

Using Java 8:

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

Solution 5

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.

Share:
1,289,380
DVK
Author by

DVK

Areas of expertise: Perl expert (specifically enterprise software development Sybase (table design, query optimization and stored proc development) Java (including Reflection and Javascript embedding) Areas of familiarity: Web programming (EmbPerl, JSP, CSS, HTML, JavaScript) C++ Shell scripting, *nix system administration

Updated on June 16, 2020

Comments

  • DVK
    DVK almost 4 years

    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.

  • Sean A.O. Harney
    Sean A.O. Harney over 14 years
    There is no need to check if f != null before checking f.exists, if the new keyword fails it will generate an Exception.
  • just somebody
    just somebody over 14 years
    there's no check if f != null. f + (...) uses java.io.File.toString
  • demongolem
    demongolem over 12 years
    Way to not answer the question. I agree commons has a lot of useful stuff, but maybe we could take that one step further and provide an answer to the question the OP asked.
  • bulltorious
    bulltorious over 11 years
    He gave enough of an answer for me.
  • lmat - Reinstate Monica
    lmat - Reinstate Monica over 11 years
    Does pearl's -e also ensure that the application "can read" the file?
  • GreenGiant
    GreenGiant over 11 years
    @just actually, it uses String.valueOf(), which handles nulls
  • Doug Hauf
    Doug Hauf over 10 years
    What if I want to check every hour to see if a file has been deposited on a directly location. I have a webMethods project that has to check to see if a specific file has been uploaded to a specific drive. How would this be done. Let's say that I want to check every hour to see if the file is there. I can use Java to write a class that does this probably with a timer of some sort.
  • Nick Frolov
    Nick Frolov almost 10 years
    Catching an exception is way more expensive. In my test, checking new File().exists() was more than 10 times faster than catching FileNotFoundException. So, if you have a scenario where files normally expected to be missing (such as disk cache), exception is wrong. Also, second-guessing the system is cool.
  • user207421
    user207421 over 9 years
    @Gnawer You haven't addressed any of the issues I raised; the exception is only thrown when the file can't be opened; and operations that occur once an hour don't require micro-optimization. Your final sentence is nonsense.
  • Matthew Read
    Matthew Read almost 9 years
    @ylun.ca The example includes subdirectories? If you mean to ask whether, given a current directory of /path, new File("file.txt").exists() will return true if the correct full path is /path/to/file.txt, the answer is a big no (unless another file /path/file.txt exists).
  • Raghu K Nair
    Raghu K Nair over 7 years
    What is the advatages compared to new File(path).exists() ? For a palin exists check
  • CAW
    CAW about 7 years
    There are some cases where exists() will return an incorrect result. For example, when using an NFS file system there is an issue with stale file handles: bugs.java.com/bugdatabase/view_bug.do?bug_id=5003595 It's kind of obscure, but has been the cause of some frustrating bugs in production code before.
  • Matthieu
    Matthieu about 7 years
    @RaghuKNair java.nio.file.Files.exists() is a lot faster than java.io.File.exists() (from my small benchmark on the only computer I tested: Windows Server 2012 running Java 1.7.0_45 x64).
  • Mike C
    Mike C almost 7 years
    Files.exists() takes two arguments. Typically, you'll want something like Files.exists(path, LinkOption.NOFOLLOW_LINKS ).
  • PowerFlower
    PowerFlower almost 7 years
    @MikeC I wonder which method gets called without the second argument. The Docu doesn't even show any information about that.
  • Dan Passaro
    Dan Passaro over 6 years
    @DougHauf in your case there's no issue since you don't attempt to do anything after you check existence. But the OP asked specifically to check before opening. In this case it's better to just try/catch the file open.
  • ParkerHalo
    ParkerHalo over 6 years
    I just tried it myself and java.nio.file.Files.exists() was 5 times SLOWER than java.io.File.exists. (Win7 Java 1.7.0_79 - x86)
  • TK8
    TK8 over 6 years
    @PowerFlower: There is only one Files.exists() method. Without passing the second argument, it still calls the same method. The second argument is varargs variable and can pass 0 or more LinkOptions.
  • Genaut
    Genaut over 6 years
    From sonar docs: The Files.exists method has noticeably poor performance in JDK 8, and can slow an application significantly when used to check files that don't actually exist. The same goes for Files.notExists, Files.isDirectory and Files.isRegularFile. The best alternative to this is: path.toFile().exists()
  • Richard
    Richard over 6 years
    This also has the disadvantage that Paths.get throws an exception if the string isn't valid
  • user207421
    user207421 about 6 years
    May not work why not? And how does using a URI fix that?
  • iviorel
    iviorel about 6 years
    We had an issue. f.exists() was true and we even could get the file content. The problem was, the path was wrong but the file name was OK, even this was another file. Changing the constructor call with URI, fixed the problem.
  • Leon
    Leon over 5 years
    Use if(f.isFile()) instead.
  • Asim
    Asim about 5 years
    remember to use filePathString.trim() to avoid white spaces
  • Cristian
    Cristian about 5 years
    To take into account your answer has the best performance compared with File.is Exist() orFiles.isRegularFile() in JDK 8
  • user207421
    user207421 over 2 years
    The question is about opening it for reading, not writing, and in any case this is certainly not 'good coding practice'.
  • user207421
    user207421 over 2 years
    Hard to believe. Using a URI and changing \ to / can't have that effect. You must have fixed something else at the same time.
  • Lii
    Lii over 2 years
    Duplicate of an earlier answer.
  • qualebs
    qualebs about 2 years
    It is not uncommon to find Apache Commons Libs are already in use in most projects. I think this answer is very helpful. I can't count the number of times I reinvented the wheel before I finally started using Apache Commons. +1 from me
  • tedtanner
    tedtanner almost 2 years
    To clarify @Leon's response, f.isFile() returns false if f is a directory or if it doesn't exist. Thus, it is (mostly) equivalent to f.exists() && !f.isDirectory(), though the latter expresses intent more explicitly.