如何检查文件是否存在于 Java 中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1816673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:56:02  来源:igfitidea点击:

How do I check if a file exists in Java?

javafile-ioiofile-exists

提问by DVK

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

在打开文件以在Java(相当于Perl 的-e $filename)中读取之前,如何检查文件是否存在?

The only similar question on SOdeals with writing the file and was thus answered using FileWriterwhich is obviously not applicable here.

关于 SO的唯一类似问题涉及编写文件,因此使用FileWriterwhich 显然不适用于这里。

If possible I'd prefer a real APIcall 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.

如果可能的话,我更喜欢一个真正的API调用返回真/假,而不是一些“调用 API 打开一个文件并在它抛出一个异常时捕获它,你检查文本中的“无文件””,但我可以忍受后者。

采纳答案by Sean A.O. Harney

Using java.io.File:

使用java.io.File

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

回答by Francis Upton IV

You can use the following: File.exists()

您可以使用以下内容: File.exists()

回答by just somebody

first hit for "java file exists" on google:

在谷歌上第一次点击“java文件存在”:

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 "));
    }
}

回答by peter.murray.rust

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.htmlThis has additional methods for managing files and often better than JDK.

熟悉 Commons FileUtils https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FileUtils.html这也有额外的方法来管理文件和通常比JDK更好。

回答by Chris Dail

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.

我建议使用isFile()而不是exists(). 大多数情况下,您不仅要检查路径是否指向文件,而且要检查它是否存在。请记住,exists()如果您的路径指向目录,则返回 true。

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.

new File("C:/").exists()将返回 true 但不允许您将其作为文件打开和读取。

回答by jhumble

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

回答by rizwan

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:

这不会创建物理文件。将只创建类 File 的对象。要物理创建文件,您必须明确创建它:

f.createNewFile();

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

所以f.exists()可以用来检查这样的文件是否存在。

回答by user207421

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:

别。只要抓住FileNotFoundException.文件系统无论如何都要测试文件是否存在。这样做两次没有意义,有几个理由不这样做,例如:

  • 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 anyresource is available is just to try to use it.

不要试图猜测系统。它知道。不要试图预测未来。一般来说,测试任何资源是否可用的最好方法就是尝试使用它。

回答by Wonil

By using nio in Java SE 7,

通过在 Java SE 7 中使用 nio,

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 existsand notExistsreturn false, the existence of the file cannot be verified. (maybe no access right to this path)

如果两个existsnotExists返回false,该文件的存在,无法验证。(可能没有访问此路径的权限)

You can check if pathis a directory or regular file.

您可以检查path是目录还是常规文件。

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

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

Please check this Java SE 7 tutorial.

请查看此Java SE 7 教程

回答by user3618182

If you want to check for a Filein a directory dir

如果要检查File目录中的 adir

String directoryPath = dir.getAbsolutePath()
boolean check = new File(new File(directoryPath), aFile.getName()).exists();

and check the checkresult

并检查check结果