如果您使用Apache Commons IO,那么它是单线的:
FileUtils.deleteDirectory(dir);
请参阅FileUtils.deleteDirectory()
番石榴曾经支持类似的功能:
Files.deleteRecursively(dir);
几个版本之前已将其从Guava中删除。
虽然以上版本非常简单,但也很危险,因为它在不告诉您的情况下做出了许多假设。因此,尽管在大多数情况下它是安全的,但我更喜欢“官方方式”来做到这一点(自Java7起):
public static void deleteFileOrFolder(final Path path) throws IOException { Files.walkFileTree(path, new SimpleFileVisitor<Path>(){ @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { Files.delete(file); return CONTINUE; } @Override public FileVisitResult visitFileFailed(final Path file, final IOException e) { return handleException(e); } private FileVisitResult handleException(final IOException e) { e.printStackTrace(); // replace with more robust error handling return TERMINATE; } @Override public FileVisitResult postVisitDirectory(final Path dir, final IOException e) throws IOException { if(e!=null)return handleException(e); Files.delete(dir); return CONTINUE; } });};


