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

本文翻译自: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? 在打开文件以便在Java中读取之前,如何检查文件是否存在? (equivalent of Perl's -e $filename ). (相当于Perl的-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. 关于SO的唯一类似问题涉及编写文件,因此使用FileWriter回答,这显然不适用于此处。

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. 如果可能的话,我更喜欢真正的API调用返回true / false,而不是某些“调用API来打开文件并在它抛出异常时捕获,你在文本中检查'没有文件'”,但我可以忍受后者。


#1楼

参考:https://stackoom.com/question/7cbB/如何检查Java中是否存在文件


#2楼

File f = new File(filePathString); 

This will not create a physical file. 这不会创建物理文件。 Will just create an object of the class File. 将只创建类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. 所以f.exists()可以用来检查这样的文件是否存在。


#3楼

Don't. 别。 Just catch the FileNotFoundException. 只需捕获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. 一般来说,测试任何资源是否可用的最佳方法就是尝试使用它。


#4楼

Using java.io.File : 使用java.io.File

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

#5楼

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

扫描二维码关注公众号,回复: 10719301 查看本文章

#6楼

first hit for "java file exists" on google: 在谷歌上首次点击“java file exists”:

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 "));
    }
}
发布了0 篇原创文章 · 获赞 137 · 访问量 84万+

猜你喜欢

转载自blog.csdn.net/xfxf996/article/details/105412410