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

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

问题描述

我使用的Windows 7与Java 7更新6,发现这种奇怪(至少对我来说)行为

-
我有两个文件 E:\delete1 .txt E:\delete2.txt 都是只读文件,当我尝试删除文件时它被删除没有任何问题 - $ / b>
$ b

 文件文件=新文件(E:\\delete1.txt) ; 
assertTrue(file.delete());

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

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



,则抛出 java.nio.file.AccessDeniedException

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

解决方案

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


如果我们尝试从命令窗口中删除文件,然后窗口抛出相同的(拒绝访问)错误,但文件从资源管理器窗口中删除。它出现了 File#delete()有一个错误的实现,新的 Files#delete(Path)


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());

But when I delete file using nio API like following -

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

It throws java.nio.file.AccessDeniedException.

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

解决方案

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.

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

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