How do I check if a file exists in Java?

How can I check whether a file exists, before opening it for reading in Java? (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 text", but I can live with the latter.


使用java.io.File

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

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.


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 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.

链接地址: http://www.djcxy.com/p/13330.html

上一篇: Android中的端点出错:GoogleAuthIOException

下一篇: 如何检查Java中是否存在文件?