发现 File.mkdirs() 失败的原因
如果我在 Java 中调用 File.mkdir()
或 File.mkdirs()
方法之一,并且它返回 false
,是否存在如何知道为什么未创建目录?
If I call one of the methods File.mkdir()
or File.mkdirs()
in Java, and it returns false
, is there a way to know why was the directory not created?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不完全是,不。如果未抛出
SecurityException
,则最可能的原因是路径中的拼写错误,这意味着您意外地指定了新目录的父路径,该路径在某种程度上无效。我不认为您将其包装在
try { ... } catch (Exception e)
块中,您没有意识到正在抛出SecurityException
,因为您正在捕获SecurityException
的祖先,是吗?如果您坚信一切看起来都正确,但仍然失败,我想您可以简单地将其放入循环中重试,例如三次。如果它仍然失败,并且根据您的应用程序,您可能会在 UI 级别发出某种警报,或者将错误记录在日志文件中(假设您可以写入它)。
我认为一些更深层次的 I/O 问题可能会阻止它工作,但除了简单地通知用户发生故障之外,您在应用程序级别可以(或真正应该)做的不多。如果 I/O 存在更深层次的错误,则更有可能是系统/硬件/操作系统的问题,或者是您无法控制的完全不稳定的问题,例如子系统/服务崩溃。
...如果发生这种情况,则由 IT 人员负责修复,而不是您的应用程序。当然,除非您的应用程序以某种方式导致崩溃。
Not really, no. If a
SecurityException
is NOT thrown, then the most likely cause is a typo in the path, meaning you've accidentally specified a parent path to the new directories that is somehow invalid.I don't suppose you have it wrapped in a
try { ... } catch (Exception e)
block, where you don't realize aSecurityException
is being thrown, because you're catching an ancestor ofSecurityException
, do you?If you have a high belief that everything looks right, and it still fails, I suppose you could simply put it in a loop to retry, say, three times. If it still fails, and depending on your application, you might raise some kind of alert at the UI level, or log the error in a log file (assuming you can write to it).
I suppose it's possible that some deeper I/O issue is preventing it from working, but beyond simply notifying the user of a failure there isn't much you can (or really should) do at an application level. If there's something deeper in the I/O wrong, that's more likely a problem with the system/hardware/OS, or something completely wonky that you have no control over like a subsystem/service crash.
...and if that's happening, that's the responsibility of the IT guy to fix, not your application. Unless of course your app is somehow causing the crash.
我在 UNC 路径上的 Windows 上遇到 mkdirs() 失败。
代码如下所示:
似乎涉及某种缓存,exists() 返回 false(不存在),但文件系统上的 mkdir 失败,因为它确实存在。重新创建 File() 条目或延长超时时间并没有产生任何影响。
我在 elasticsearch 上发现了一个插件,可以修复 Windows 上的 SMB 问题。研究解决方案,它使用 nio.file 而不是 io.File。重写函数解决了这个问题:
createDirectories() 有时会失败,但会在 mkdirs() 不会的情况下恢复。
I had a mkdirs() failure on windows on a UNC path.
The code looks like this:
There appears to be some sort of caching involved where exists() returns false (does not exists) but the mkdir on the file system fails because it does exist. Recreating the File() entry or lengthing the timeout did not make a difference.
I discovered a plugin on elasticsearch to fix a SMB problem on Windows. Researching the solution, it uses nio.file instead of io.File. Rewriting the function fixed the issue:
createDirectories() sometimes fail, but recovers where mkdirs() does not.