java Files#delete(Path) 和 File#delete() 的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12139482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between Files#delete(Path) and File#delete()
提问by Premraj
I'm using Windows-7 with java 7 update 6 and found this weird (at least to me) behavior -
I have two files E:\delete1.txt
and E:\delete2.txt
both are read onlyfiles, when I try to delete file like following it gets deleted without any issues -
我正在使用带有 java 7 update 6 的 Windows-7 并发现这种奇怪的(至少对我而言)行为 -
我有两个文件,E:\delete1.txt
而且E:\delete2.txt
都是只读文件,当我尝试删除文件时,如下所示,它会被删除而没有任何问题 -
File file = new File("E:\delete1.txt");
assertTrue(file.delete());
But when I delete file using nio API like following -
但是当我使用 nio API 删除文件时,如下所示 -
Path path = Paths.get("E:\delete2.txt");
Files.delete(path);
It throws java.nio.file.AccessDeniedException
.
它抛出java.nio.file.AccessDeniedException
.
Why different behavior for same operation with old and new nio API?
为什么使用新旧 nio API 进行相同操作的行为不同?
采纳答案by Premraj
As discussed here- The issue is that java.io.File
has many oddities, on Windows in
particular. In this case it resets the file attributes before it deletes
the file so this is why it does not fail as might be expected. It is
behavior that dates back >10 years and so would be risky to change now.
It has several other oddities like this, just one of the reason why it
wasn't re-implemented to use the new API.
If we try to delete the file from command window then windows throws the same (Access denied) error but file gets deleted from explorer window. It appears the File#delete()
has a wrong implementation and new Files#delete(Path)
should be preferred instead.
正如这里所讨论的- 这个问题java.io.File
有很多奇怪之处,尤其是在 Windows 上。在这种情况下,它会在删除文件之前重置文件属性,因此这就是它不会像预期的那样失败的原因。这种行为可以追溯到 10 年以上,因此现在改变是有风险的。它还有其他几个像这样的奇怪之处,这只是它没有重新实现以使用新 API 的原因之一。
如果我们尝试从命令窗口中删除文件,则 Windows 会抛出相同的(拒绝访问)错误,但文件会从资源管理器窗口中删除。似乎File#delete()
有一个错误的实现,Files#delete(Path)
应该首选new 。
回答by Michael Borgwardt
Why different behavior for same operation with old and new nio API?
为什么使用新旧 nio API 进行相同操作的行为不同?
Because exactly emulating the behaviour of the old API for similar operations was apparently not considered an important goal in the design of the new API. Given that the main goal of the nio filesystem API was to present a newAPI with some quite different underlying concepts and a lot of new capabilities, it seems pretty normal to me.
因为在新 API 的设计中,针对类似操作准确模拟旧 API 的行为显然不是一个重要目标。鉴于 nio 文件系统 API 的主要目标是提供一个具有一些完全不同的基础概念和许多新功能的新API,这对我来说似乎很正常。