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

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

问题描述

如果我这样做:
$ b $ pre $ 文件f =新文件(c:\\text.txt) ;

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

然后文件被创建并且总是返回File exists。是否有可能检查一个文件是否存在而不创建它?



编辑:

<我忘记提到它在for循环。所以这里是真实的:
$ b $ pre $ for(int i = 0; i <10; i ++){
File file = new File(c:\\text+ i +.txt);
System.out.println(New file created:+ file.getPath());


解决方案

c $ c> File ,你不是在磁盘上创建任何东西,而只是建立一个可以调用某些方法的对象,如 exists()

这很好也很便宜,不要试图避免这种情况。



<$ c
$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $'
私有瞬态int prefixLength;

这里是构造函数:

<$ p (); $ p> 237 public File(String pathname){
238 if(pathname == null){
239 throw new NullPointerException();
240}
241 this.path = fs.normalize(pathname);
242 this.prefixLength = fs.prefixLength(this.path);
243
code $


正如你所看到的, File instance仅仅是路径的封装。创建它以调用 exists()是正确的方法。不要试图优化它。


If I do this:

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?

EDIT:

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

解决方案

When you instanciate 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 instanciation.

The File instance has only two fields :

private String path;
private transient int prefixLength;

And here is the constructor :

237     public File(String pathname) {
238         if (pathname == null) {
239             throw new NullPointerException();
240         }
241         this.path = fs.normalize(pathname);
242         this.prefixLength = fs.prefixLength(this.path);
243     }

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天全站免登陆