tags:

views:

1270

answers:

7

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

The only similar question on SO dealt 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 text", but I can live with the latter.

+15  A: 

Using java.io.File

File f = new File(filePathString);
if(f.exists()) { /* do something */ }
Sean A.O. Harney
Note that `exists()` will return `true` for directories, too!
Paul Lammertsma
+1  A: 

Use File.exists()

Francis Upton
+2  A: 

The Java API is really quite good. See this entry on the File class.

Stefan Kendall
+2  A: 

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 "));
  }
}
just somebody
The API docs were on display in the bottom of a locked filing cabinet, stuck in a disused lavatory, with a sign on the door saying 'Beware of the Leopard'.
skaffman
There is no need to check if f != null before checking f.exists, if the new keyword fails it will generate an Exception.
Sean A.O. Harney
there's no check if f != null. f + (...) uses java.io.File.toString
just somebody
+2  A: 

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

peter.murray.rust
+10  A: 

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.

Chris Dail
+1 Very useful to know, thanks
James
A: 
f.isFile() && f.canRead()
jhumble