检查文件是否存在,而不创建它 [英] Check if file exists without creating it
问题描述
如果我这样做:
$ 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;
这里是构造函数: 正如你所看到的, If I do this: 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:
When you instanciate a That's fine and cheap, don't try to avoid this instanciation. The And here is the constructor : As you can see, the 这篇关于检查文件是否存在,而不创建它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
<$ 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()
是正确的方法。不要试图优化它。File f = new File("c:\\text.txt");
if (f.exists()) {
System.out.println("File exists");
} else {
System.out.println("File not found!");
}
for (int i = 0; i < 10; i++) {
File file = new File("c:\\text" + i + ".txt");
System.out.println("New file created: " + file.getPath());
}
File
, you're not creating anything on disk but just building an object on which you can call some methods, like exists()
.File
instance has only two fields :private String path;
private transient int prefixLength;
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 }
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.