简体   繁体   English

Java,如何检查文件是否存在

[英]Java, how to check the existence of file

I have this small code 我有这个小代码

    File source;
    if ( !source.exists() ) {
        source = new File("instances/student"+student.getStudentID()+".data");
    }

The problem is, source is not initialized. 问题是,源未初始化。 Since the whole point is to check if it exists, how do I avoid this? 既然要检查它是否存在,如何避免这种情况?

Create a File object. 创建一个File对象。

File source = new File(...);

What constructor you use depends on how you want to locate a file. 使用哪种构造函数取决于您如何查找文件。 A simple path String could be enough. 一个简单的路径String就足够了。

EDIT: just realized the source of your confusion may be that you think creating the File object will try to locate the file or create it on the file system. 编辑:刚刚意识到您的困惑的根源可能是您认为创建File对象将尝试查找文件或在文件系统上创建它。 That's not the case. 事实并非如此。 Just calling new File(...) won't check its existence or try to create it. 仅调用new File(...)不会检查其存在或尝试创建它。 A File object is simply an abstraction for a path in your file system. File对象只是文件系统中路径的抽象。 It could be a directory as well. 也可以是目录。

You can do: 你可以做:

File f = new File(somepathhere);
if ( !f.exists() ) {
    f = new File("instances/student"+student.getStudentID()+".data");
}

Or you can check if f.isFile() 或者您可以检查f.isFile()

You seem to have a misunderstanding. 您似乎有一个误会。 Creating a File doesn't create a file on the file system. 创建文件不会在文件系统上创建文件。 A File object only really represents a filename. File对象仅真正代表文件名。 If you want to see whether a file exists, create a File of the appropriate name and check exists() . 如果要查看文件是否存在,请创建一个具有适当名称的File并检查exists()

But then if you want to overwrite or append to a file you don't even need all that. 但是,如果您要覆盖或附加到文件,则甚至不需要这些。 Just create a new FileOutputStream(...) , with the append parameter set to true if you want to append. 如果要追加,只需创建一个new FileOutputStream(...)append参数设置为true即可。 No need to check beforehand, in fact it is more than a waste of time. 无需事先检查,实际上这不只是浪费时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM