静态检查文件是否存在
我想知道是否存在某种方法来检查文件是否存在而不创建 java.io.File
实例
我总是使用以下方法:
File f = new File("./path/to/file");
if (f.exists()) {
doSomething();
}
else {
manageError();
}
但知道我需要检查一些文件路径才能创建诸如记录器(使用 log4j)、xml 编辑器和其他项目结构之类的元素,但我不需要使用它们。
出于这个原因,我想知道这是否可能。
我正在使用 J2SE-1.5_22。
提前致谢!
I'm wondering if exist some way to check if a file exist without create an instance of java.io.File
Always I have used the following way:
File f = new File("./path/to/file");
if (f.exists()) {
doSomething();
}
else {
manageError();
}
But know I need check some filepaths in order to create elements like a logger (with log4j), xml editor and other project structures, but I don't need work with them.
For this reason I want to know if this is possible.
I'm using J2SE-1.5_22.
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不明白你已经做的事情有什么问题。创建
File
实例不会在磁盘或任何其他内容上创建文件。如果您愿意,您始终可以编写静态方法:如果这不能满足您的要求,请解释您正在尝试执行的操作与此方法无关。
I don't see what's wrong with what you're already doing. Creating an instance of
File
isn't going to create the file on disk or anything. You could always write a static method if you want:If that doesn't satisfy your requirements, please explain what you're trying to do that doesn't work with this.
我认为
java.io.File
的原始作者假设,如果您正在检查文件是否存在,那么您可能会对其执行某些操作:如果存在则修改它,或者如果存在则创建一个新文件事实并非如此。Jon 的解决方案是一种解决方法,您可能应该将其添加到您的
Utils
中。File
对象非常轻量级并且很容易被丢弃。I think the original the authors of
java.io.File
assumed that if you're checking for a file's existence then you will probably do something with it: modify it if it exists or create a new file if it doesn't.Jon's solution is a workaround you should probably add to your
Utils
. TheFile
objects are pretty lightweight and easily discarded.另一种方法是使用私有 Java 类。虽然我不会建议这样做,除非你知道自己在做什么。
类似的:
虽然这段代码本身无法工作,因为 FileSystem 是一个私有类,但是通过反射将其更改为公共类,它应该可以工作。
Another way would use private Java classes. Though I wouldn't suggest it, unless you know what you're doing.
Something like:
Though this code won't work on its own since FileSystem is a private class, but change it to a public class with reflection and it should work.