检查文件是否存在而不创建它 [英] Check if file exists without creating it

查看:27
本文介绍了检查文件是否存在而不创建它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我这样做:

File f = new File("c:\text.txt");

if (f.exists()) {
    System.out.println("File exists");
} else {
    System.out.println("File not found!");
}

然后文件被创建并总是返回文件存在".是否可以在不创建文件的情况下检查文件是否存在?

Then the file gets created and always returns "File exists". Is it possible to check if a file exists without creating it?

我忘了提到它在 for 循环中.所以这是真实的:

I forgot to mention that it's in a for loop. So here's the real thing:

for (int i = 0; i < 10; i++) {
    File file = new File("c:\text" + i + ".txt");
    System.out.println("New file created: " + file.getPath());
}

推荐答案

当你实例化一个 File 时,你不是在磁盘上创建任何东西,而是创建一个可以调用一些方法的对象, 就像 exists().

When you instantiate a File, you're not creating anything on disk but just building an object on which you can call some methods, like exists().

这很好也很便宜,不要试图避免这种实例化.

That's fine and cheap, don't try to avoid this instantiation.

File 实例只有两个字段:

private String path;
private transient int prefixLength;

这是构造函数:

public File(String pathname) {
    if (pathname == null) {
        throw new NullPointerException();
    }
    this.path = fs.normalize(pathname);
    this.prefixLength = fs.prefixLength(this.path);
}

如您所见,File 实例只是路径的封装.创建它以调用 exists() 是正确的方法.不要试图优化它.

As you can see, the File instance is just an encapsulation of the path. Creating it in order to call exists() is the correct way to proceed. Don't try to optimize it away.

这篇关于检查文件是否存在而不创建它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆