症狀很簡單:Windows拒絕刪除一個目錄,因爲它認爲它的內容仍然存在 - 雖然遞歸刪除只是刪除它們。所以我的第一個猜測是在刪除它的內容之後並在刪除它之前,父目錄上出現了衝突/同步或類似的缺失。沒有可靠的遞歸目錄刪除可能嗎?
我試着公地IO 2.5版FileUtils.deleteDirectory和FileUtils.cleanDirectory功能,以及我自己的簡化測試:
@Test
public void testMySimpleDelete() throws IOException, InterruptedException {
File dir = TEST_DIR;
for (int i = 0; i < 10; i++) {
dir = new File(dir, Integer.toString(i));
}
for (int i = 0; i < 1000; i++) {
LOG.info(""+i);
assertTrue("loop #" + i, dir.mkdirs());
mySimpleDelete(Paths.get(TEST_DIR.getAbsolutePath()));
assertFalse(TEST_DIR.exists());
}
}
private void mySimpleDelete(Path file) throws IOException, InterruptedException {
Files.walkFileTree(file, new FileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
//LOG.info(dir.toString());
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
無不顯示出相同的結果/症狀。
如果你想自己驗證這個行爲(僅限於Windows!Linux根本不鎖定任何東西,並且行爲方式更加寬鬆),只需檢查https://github.com/jjYBdx4IL/java-evaluation並運行「mvn test -Dtest = org.apache .commons.io.FileUtilsTest」。
參見http://stackoverflow.com/q/22948189/886887 –