问题是如果包含某些内容,您将无法删除目录。所以你必须递归删除目录的内容!
在 Java 7 中:
public class DeleteDirVisitor extends SimpleFileVisitor<Path> {
private Path baseDir;
public DeleteDirVisitor() {
}
/**
* If baseDir is specified all the subdirectory will be deleted but not basedir
*
* @param baseDir
*/
public DeleteDirVisitor(Path baseDir) {
this.baseDir = baseDir;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {
if ((baseDir == null) || !dir.equals(baseDir)) {
Files.delete(dir);
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
}
并使用:
Files.walkFileTree(Paths.get(new File("Your Path").getAbsolutePath()), new DeleteDirVisitor());