Javaでディレクトリを再帰的に削除する方法をメモしておきます。たった1行で実現してみます。
環境
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- Java 11 |
SpringのFileSystemUtilsを利用する
Springフレームワークを利用している場合は、Springが提供しているFileSystemUtilsを利用するのがおすすめです。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
boolean isDeleted = FileSystemUtils.deleteRecursively(new File("/path/to/directory")); |
commons-ioのFileUtilsを利用する
commons-ioのFileUtilsを利用しても1行で書けます。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
FileUtils.deleteDirectory(new File("/path/to/directory")); |
まとめ
Javaでディレクトリを再帰的に削除する方法でした。