尝试对从Delete directories recursively in Java
取得的递归删除方法中的偶然java.nio.file.DirectoryNotEmptyException
进行问题排查
代码(归功于@TrevorRobinson):
static void removeRecursive(Path path) throws IOException {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
final Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs) throws IOException {
logger.warn("Deleting " + file.getFileName());
Files.delete(file);
logger.warn("DELETED " + file.getFileName());
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
// try to delete the file anyway, even if its attributes could
// not be read, since delete-only access is theoretically possible
// I NEVER SEE THIS
logger.warn("Delete file " + file + " failed", exc);
try {
Files.delete(file);
} catch (IOException e) {
logger.warn(
"Delete file " + file + " failed again", exc);
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc)
throws IOException {
if (exc == null) {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
// directory iteration failed; propagate exception
throw exc;
}
});
}
拨打:
try {
removeRecursive(Paths.get(unzipDirPath));
} catch (IOException e) {
String msg = "Failed to delete folder " + unzipDirPath;
if (e instanceof java.nio.file.DirectoryNotEmptyException) {
msg += ". Still contains : ";
final File[] listFiles = Paths.get(unzipDirPath).toFile().listFiles();
if (listFiles != null) for (File file : listFiles) {
msg += file.getAbsolutePath() + "\n";
}
}
log.error(msg, e);
}
打印(一次在20/40次迭代中):
22:03:34.190 [http-bio-8080-exec-47] WARN g.u.d.m.server.servlets.Controller$1 - Deleting batt
22:03:34.192 [http-bio-8080-exec-47] WARN g.u.d.m.server.servlets.Controller$1 - DELETED batt
22:03:34.192 [http-bio-8080-exec-47] WARN g.u.d.m.server.servlets.Controller$1 - Deleting wifi
22:03:34.193 [http-bio-8080-exec-47] WARN g.u.d.m.server.servlets.Controller$1 - DELETED wifi
22:03:34.196 [http-bio-8080-exec-47] ERROR g.u.d.m.s.s.DataCollectionServlet - Failed to delete folder C:\yada\. Still contains : C:\yada\dir\wifi
java.nio.file.DirectoryNotEmptyException: C:\yada\dir
at sun.nio.fs.WindowsFileSystemProvider.implDelete(WindowsFileSystemProvider.java:265) ~[na:1.7.0_45]
at sun.nio.fs.AbstractFileSystemProvider.delete(AbstractFileSystemProvider.java:103) ~[na:1.7.0_45]
at java.nio.file.Files.delete(Files.java:1077) ~[na:1.7.0_45]
at gr.uoa.di.monitoring.server.servlets.Controller$1.postVisitDirectory(Controller.java:128) ~[Controller$1.class:na]
at gr.uoa.di.monitoring.server.servlets.Controller$1.postVisitDirectory(Controller.java:1) ~[Controller$1.class:na]
at java.nio.file.FileTreeWalker.walk(FileTreeWalker.java:224) ~[na:1.7.0_45]
at java.nio.file.FileTreeWalker.walk(FileTreeWalker.java:199) ~[na:1.7.0_45]
at java.nio.file.FileTreeWalker.walk(FileTreeWalker.java:69) ~[na:1.7.0_45]
at java.nio.file.Files.walkFileTree(Files.java:2600) ~[na:1.7.0_45]
at java.nio.file.Files.walkFileTree(Files.java:2633) ~[na:1.7.0_45]
at gr.uoa.di.monitoring.server.servlets.Controller.removeRecursive(Controller.java:96) ~[Controller.class:na]
at gr.uoa.di.monitoring.server.servlets.DataCollectionServlet.doPost(DataCollectionServlet.java:153) ~[DataCollectionServlet.class:na]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641) [servlet-api.jar:na]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722) [servlet-api.jar:na]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) [catalina.jar:7.0.32]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) [catalina.jar:7.0.32]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222) [catalina.jar:7.0.32]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123) [catalina.jar:7.0.32]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) [catalina.jar:7.0.32]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168) [catalina.jar:7.0.32]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) [catalina.jar:7.0.32]
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929) [catalina.jar:7.0.32]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) [catalina.jar:7.0.32]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) [catalina.jar:7.0.32]
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1002) [tomcat-coyote.jar:7.0.32]
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585) [tomcat-coyote.jar:7.0.32]
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) [tomcat-coyote.jar:7.0.32]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [na:1.7.0_45]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [na:1.7.0_45]
at java.lang.Thread.run(Thread.java:744) [na:1.7.0_45]
请注意,wifi
被报告为已删除 - 更奇怪的是有时我会得到:
无法删除文件夹C:\ yada。仍然包含:C:\ yada \ dir
java.nio.file.DirectoryNotEmptyException:C:\ yada \ dir
我倾向于得出这样的结论:偶尔删除时间太长 - 换句话说,问题是java.nio.file.Files.delete(Path path)
没有阻塞(因此C:\ yada \ dir在时间到来时仍然包含文件,有时候是删除时我统计它)。那么我该如何解决这个问题呢?
:是否需要java.nio.file.Files.delete(Path path)
投掷? docs州:
在某些操作系统上,当该文件在此Java虚拟机或其他程序中打开并正在使用时,可能无法删除该文件。
在这种情况下似乎不需要抛出异常。 是否需要java.nio.file.Files.delete(Path path)
投掷?
答案 0 :(得分:11)
我遇到了同样的问题,事实证明这个问题是由我在删除内容的同一目录的代码中的其他地方的未封闭目录文件流引起的。返回的流对象:
Files.list(Path)
必须关闭,因此如果使用该方法,请务必在代码中使用try-with-resources构造。
所以我不认为删除时间太长,我尝试等待重新尝试删除目录而没有任何运气。您自己的程序最有可能锁定该资源。结果是,虽然它成功返回,但它的删除调用并没有完成(看起来Windows最终会在你自己的程序释放后删除文件)但当然包含的目录无法删除,因为它确实是还没空。
答案 1 :(得分:2)
我知道这是一个非常老的线程 - 但我遇到了同样的问题,我花了很长时间才解决它。 我认为这种不当行为是由计时问题造成的(看起来只发生在Windows上),所以我在postVisitDirectory方法中暂停了一下。这很有效,这就是我最终想出来的:
执行删除而不抛出DirectoryNotEmptyException的方法:
private boolean isDeleted(Path dir) throws IOException {
boolean deleted = false;
try {
Files.delete(dir);
deleted = true;
} catch (DirectoryNotEmptyException e) {
// happens sometimes if Windows is too slow to remove children of a directory
deleted = false;
}
return deleted;
}
及其在循环中的使用:
public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {
if (e == null) {
int maxTries = 5;
int count = 0;
boolean deleted = false;
do {
if ((deleted = this.isDeleted(dir))) {
break;
} else {
// wait a bit and try again
count++;
try {
Thread.sleep(1);
} catch (InterruptedException e1) {
Thread.currentThread().interrupt();
break;
}
}
} while (count < maxTries);
// gone?
if (!deleted) {
throw new DirectoryNotEmptyException(dir.toString());
}
// go ahead
return FileVisitResult.CONTINUE;
}
throw e;
}
安迪
答案 2 :(得分:0)
您可以暂时将当前正在迭代的文件的名称存储在变量中,并在DirectoryNotEmptyException
上执行try-catch。发生此异常时,捕获它并抛出指定文件的异常。
try {
Files.delete(file);
} catch (DirectoryNotEmptyException e) {
throw new MySpecificException(file.getFileName());
}
class MySpecificException extends Exception {
public MySpecificException() { }
public MySpecificException(string filename) {
super(filename);
}
}
获取文件名可以使用e.getMessage();
我认为Files.delete()
在遇到无法删除的文件时会继续删除目录中的文件。如果是这种情况,我的方法仍然有效:只返回目录中所有文件的列表,而不是目录的文件名。它应该只包含无法删除的文件,您仍然可以使用解决方案。
答案 3 :(得分:0)
我会评论@ user3485962的答案,但没有足够的分数!
这是一个使用try资源的示例,该示例在创建列表后关闭流:
val name = resources.getResourceEntryName(resId)
val file = File(context.cacheDir, name)
if (!file.exists()) {
val resourceStream = resources.openRawResource(resource.res)
copyStreamToFile(resourceStream, file)
}
setVideoPath(file.absolutePath)
答案 4 :(得分:-1)
扩展我的评论。
当Java遇到问题时会抛出Exception。与所有其他类型一样,异常可以继承自。 API将指定每个方法抛出的已检查异常。 java.io
和java.nio
中的方法通常会抛出IOException
或其中一个孩子。如果你想创建一个方法来告诉你为什么文件操作(在这种情况下是删除)失败了你可以做这样的事情:
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
//You don't need to try to delete the file again since this method was called
//because the deletion failed. Instead...
if (exc instanceof NoSuchFileException) {
System.out.println("Could not find the file: " + file);
} else if (exc instanceof DirectoryNotEmptyException) {
System.out.println("The directory [+ " file + "] was not empty.");
} else {
System.out.println("Could not delete file [" + file
+ "]. There was a problem communicating with the file system");
}
return FileVisitResult.CONTINUE;
}
您可以根据需要更改实际的程序响应,但这应该为您提供一般的想法。