Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

java - Difference between Files#delete(Path) and File#delete()

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...