LoginSignup
4
7

More than 5 years have passed since last update.

Javaでディレクトリ以下を再帰的に削除

Last updated at Posted at 2017-07-28

Files#walkが、ディレクトリの上から辿ってPathオブジェクトを返してくれるので、それを利用すると、割りときれいに書けるようです。

ファイル関連はtry-with-resourcesをするのが鉄板の模様

Path dir = Paths.get("/temp");
try(Stream<path> walk = Files.walk(dir, FileVisitOption.FOLLOW_LINKS))
{
                walk.sorted(Comparator.reverseOrder())
                .map(Path::toFile)
                .forEach(File::delete);
dir .toFile().delete();
} catch (IOException ie) {
 System.out.println(ie);
}
4
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
7