Files#delete(Path) 和 File#delete() 的区别 [英] Difference between Files#delete(Path) and File#delete()

查看:21
本文介绍了Files#delete(Path) 和 File#delete() 的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 Windows-7 与 java 7 update 6 一起使用,发现这种奇怪的(至少对我而言)行为 -
当我尝试删除文件时,我有两个文件 E:delete1.txtE:delete2.txt 都是 只读 文件就像跟随它被删除没有任何问题 -

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 only files, when I try to delete file like following it gets deleted without any issues -

File file = new File("E:\delete1.txt"); 
assertTrue(file.delete());

但是当我使用 nio API 删除文件时,如下所示 -

But when I delete file using nio API like following -

Path path = Paths.get("E:\delete2.txt");
Files.delete(path);

它抛出java.nio.file.AccessDeniedException.

为什么新旧 nio API 相同操作的行为不同?

Why different behavior for same operation with old and new nio API?

推荐答案

正如讨论的 here - 问题是 java.io.File 有很多奇怪之处,在 Windows 上特别的.在这种情况下,它会在删除之前重置文件属性文件,所以这就是它不会像预期的那样失败的原因.它是可以追溯到 10 年以上的行为,因此现在改变将有风险.它还有其他几个像这样的奇怪之处,这只是它的原因之一未重新实现以使用新 API.

如果我们尝试从命令窗口中删除文件,则 Windows 会抛出相同的(拒绝访问)错误,但文件会从资源管理器窗口中删除.看起来 File#delete() 有一个错误的实现,新的 Files#delete(Path) 应该是首选.

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.

这篇关于Files#delete(Path) 和 File#delete() 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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