Java nio - cannot delete directory that has been emptied

I am trying to go through a file tree and delete all files / directories. Code below:

Files.walkFileTree(metricPath, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { if (exc == null) { Files.delete(dir); return FileVisitResult.CONTINUE; } else { throw exc; } } }); } 

This code runs between unit tests, each of which generates a separate file in the form of folder1/folder2/file . When I try to traverse this tree, The DirectoryNotEmptyException is thrown when folder 1 tries to delete, although it is clearly empty ...

+4
source share
3 answers

Have you checked this directory for hidden files? On Windows, it may be that some process opened this directory and opened the HANDLE file, it still exists in the HANDLE system table. In this case, the directory is locked, and java may pass this exception.

0
source

As I see it on your code, there should be no problem if only one file / folder is in read-only mode. You can first examine the change in file resolution before deleting.

You can also try using the Files.delete () method the next time you override

  public FileVisitResult visitFileFailed (Path file, IOException exc) 

Link: Removing JAVA NIO Directory

0
source

Alternatively, you can import Apache Commons IO and use FileUtils. deleteDirectory (File directory) . One line is enough, because it recursively deletes all files and subdirectories:

 FileUtils.deleteDirectory(dirToBeDeleted); 
-1
source

All Articles