有没有一种正确的方法来检查Java中的文件/目录存在? [英] Is there a proper way to check for file/directory existence in Java?

查看:113
本文介绍了有没有一种正确的方法来检查Java中的文件/目录存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

 字符串dir = //目录的路径
文件saveDir =新建文件(dir);
//存在检查
if(!saveDir.exists())
saveDir.mkdirs();

这部分代码用于保存具有给定目录路径的文件到文件系统。保存之前我想检查给定的保存目录是否存在。然而,存在检查似乎没有以我想要的方式工作。如果不删除if子句,则不会创建所需的目录。在查找我的问题时,我遇到了这个有趣的堆栈问题。
替代Java中的File.exists()。据我所知,java.io有这个问题。




在 之后仍然不存在目录c $ c>条件已被评估。另一个进程或用户可以创建/删除它。所以你必须检查操作是否失败(可能捕捉到适当的异常)。

所以你不应该依赖检查,总是期望最坏的情况。 (好吧,这些检查可能有助于防止你做不必要的事情,或者要求用户进行确认等等,但是他们不保证

>

Code:

String dir = //Path to the  directory
File saveDir = new File(dir);
//Here comes the existence check
if(!saveDir.exists())
  saveDir.mkdirs();

This part of code is used to save files with a given directory path to file system. Before saving i want to check whether the given save directory exists. However the existence check do not seem to work in the way that i wanted. Without removing the if clause the desired directories are not created.I came across to this interesting stack question while searching for my problem. Alternative to File.exists() in Java. As i understand java.io has this problem.

Is there a proper and safe way to check the existance of a directory or resource while doing file operations?

解决方案

Well, even if the check would be correct, you can never be sure that the directory still exists after the if condition has been evaluated. Another process or user can just create/remove it. So you have to check if the operation fails (possibly catching the appropriate exception) anyway.

So you shouldn't rely on checks and expect the worst case always. (Well, the checks may be useful for preventing you from doing something unnecessary, or for asking user for confirmation etc. But they don't guarantee anything.)

这篇关于有没有一种正确的方法来检查Java中的文件/目录存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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