The File class allows you to delete files.
If you use File.delete()
, you can delete one file or folder, but you cannot delete it if there is a file in the folder.
In this case, you can implement to find and delete all files recursively, or use a Java library that implements these contents.
Delete all subfolders and files (Recursively)
First, the code that finds and deletes all sub-files recursively is introduced.
I made a folder in the /home/js/test/myfolder
path, and created a lot of folders and files under it.
The structure of the tree command is as follows.
/home/js/test/myfolder$ tree
.
├── file1.txt
├── folder1
│ └── file2.txt
├── folder2
│ ├── file3.txt
│ └── file4.txt
├── folder3
│ ├── file5.txt
│ ├── file6.txt
│ └── folder4
│ ├── text2.txt
│ ├── text3.txt
│ └── text.txt
└── myscript.sh
The code below recursively deletes all sub-files including the /home/js/test/myfolder
folder.
public class DeleteFilesRecursively {
public static void main(String args[]) throws ParseException {
File rootDir = new File("/home/js/test/myfolder");
deleteFilesRecursively(rootDir);
}
static boolean deleteFilesRecursively(File rootFile) {
File[] allFiles = rootFile.listFiles();
if (allFiles != null) {
for (File file : allFiles) {
deleteFilesRecursively(file);
}
}
System.out.println("Remove file: " + rootFile.getPath());
return rootFile.delete();
}
}
If File is a folder,
listFiles()
returns a list of files under that file. Returns null if File is not a folder.
When executed, the following log is output and all files are deleted.
Remove file: /home/js/test/myfolder/folder1/file2.txt
Remove file: /home/js/test/myfolder/folder1
Remove file: /home/js/test/myfolder/file1.txt
Remove file: /home/js/test/myfolder/myscript.sh
Remove file: /home/js/test/myfolder/folder3/file5.txt
Remove file: /home/js/test/myfolder/folder3/folder4/text3.txt
Remove file: /home/js/test/myfolder/folder3/folder4/text2.txt
Remove file: /home/js/test/myfolder/folder3/folder4/text.txt
Remove file: /home/js/test/myfolder/folder3/folder4
Remove file: /home/js/test/myfolder/folder3/file6.txt
Remove file: /home/js/test/myfolder/folder3
Remove file: /home/js/test/myfolder/folder2/file3.txt
Remove file: /home/js/test/myfolder/folder2/file4.txt
Remove file: /home/js/test/myfolder/folder2
Remove file: /home/js/test/myfolder
Delete subfolders, files with FileUtils
If it is cumbersome and cumbersome to implement it yourself like the example above, you can use FileUtils of the commons-io library.
Gradle project adds the following to dependencies of build.gradle
.
dependencies {
compile group: 'commons-io', name: 'commons-io', version: '2.6'
...
}
For projects that use other build systems such as Maven, refer to mvnrepository.com and configure it.
FileUtils.deleteDirectory()
deletes all files and sub-files passed as arguments.
The code below performs the same function as the code implemented directly above. If you run the code, you can see that all sub files of myfolder have been deleted.
try {
File rootDir = new File("/home/js/test/myfolder");
FileUtils.deleteDirectory(rootDir);
} catch (IOException e) {
e.printStackTrace();
}
Everything is implemented inside FileUtils, which is the cleanest and easiest way.
Delete subfolders and files using Java8
You can delete files using Java8`s Stream and Files.
You can iterate through all files and delete files like this:
try {
File rootDir = new File("/home/js/test/myfolder");
Files.walk(rootDir.toPath())
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach((file)->{
System.out.println("Remove file: " + file.getPath());
file.delete();
});
} catch (IOException e) {
e.printStackTrace();
}
When the above code is executed, the file is deleted while outputting the log as follows.
Remove file: /home/js/test/myfolder/myscript.sh
Remove file: /home/js/test/myfolder/folder3/folder4/text3.txt
Remove file: /home/js/test/myfolder/folder3/folder4/text2.txt
Remove file: /home/js/test/myfolder/folder3/folder4/text.txt
Remove file: /home/js/test/myfolder/folder3/folder4
Remove file: /home/js/test/myfolder/folder3/file6.txt
Remove file: /home/js/test/myfolder/folder3/file5.txt
Remove file: /home/js/test/myfolder/folder3
Remove file: /home/js/test/myfolder/folder2/file4.txt
Remove file: /home/js/test/myfolder/folder2/file3.txt
Remove file: /home/js/test/myfolder/folder2
Remove file: /home/js/test/myfolder/folder1/file2.txt
Remove file: /home/js/test/myfolder/folder1
Remove file: /home/js/test/myfolder/file1.txt
Remove file: /home/js/test/myfolder
You can also use File::delete
instead of the Lambda passed as an argument to File::delete
as follows.
try {
File rootDir = new File("/home/js/test/myfolder");
Files.walk(rootDir.toPath())
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
} catch (IOException e) {
e.printStackTrace();
}
If you want to implement to delete only specific files, you can also add conditional statements in forEach to delete only specific files.
Reference
Related Posts
- Java - Remove items from List while iterating
- Java - How to find key by value in HashMap
- Java - Update the value of a key in HashMap
- Java - How to put quotes in a string
- Java - How to put a comma (,) after every 3 digits
- BiConsumer example in Java 8
- Java 8 - Consumer example
- Java 8 - BinaryOperator example
- Java 8 - BiPredicate Example
- Java 8 - Predicate example
- Java 8 - Convert Stream to List
- Java 8 - BiFunction example
- Java 8 - Function example
- Java - Convert List to Map
- Exception testing in JUnit
- Hamcrest Collections Matcher
- Hamcrest equalTo () Matcher
- AAA pattern of unit test (Arrange/Act/Assert)
- Hamcrest Text Matcher
- Hamcrest Custom Matcher
- Why Junit uses Hamcrest
- Java - ForkJoinPool
- Java - How to use Futures
- Java - Simple HashTable implementation
- Java - Create a file in a specific path
- Java - Mockito의 @Mock, @Spy, @Captor, @InjectMocks
- Java - How to write test code using Mockito
- Java - Synchronized block
- Java - How to decompile a ".class" file into a Java file (jd-cli decompiler)
- Java - How to generate a random number
- Java - Calculate powers, Math.pow()
- Java - Calculate the square root, Math.sqrt()
- Java - How to compare String (==, equals, compare)
- Java - Calculate String Length
- Java - case conversion & comparison insensitive (toUpperCase, toLowerCase, equalsIgnoreCase)