Skip to content

Instantly share code, notes, and snippets.

@manzke
Last active October 5, 2017 13:20
Show Gist options
  • Select an option

  • Save manzke/5650738 to your computer and use it in GitHub Desktop.

Select an option

Save manzke/5650738 to your computer and use it in GitHub Desktop.
Delete path recursively with NIO.2
if (Files.exists(path)) {
if (Files.isDirectory(path)) {
Files.walkFileTree(path, 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 {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
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;
}
}
});
} else {
Files.deleteIfExists(path);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment