This article will show you how to delete files and directories using recursive processing. This is my first post, so if you have any comments, please comment!
/**
*Delete files recursively
* @param file File or directory to delete
*/
public static void deleteFile(File file) {
//Exit if the file does not exist
if (!file.exists()) {
return;
}
//Delete child if it is a directory
if (file.isDirectory()) {
for (File child : file.listFiles()) {
deleteFile(child);
}
}
//Delete the target file
file.delete();
}
If it is a directory, it can be deleted in an empty state by deleting the child file object first.
For a while, I was happy to be able to use recursive processing, but after all there were many pioneers ... lol It's a waste to end with this, so I'll introduce a little more advanced one!
/**
*Count only the number of files contained in a file or directory
* @param file file or directory
* @number of return files
*/
public static int countFile(File file) {
int count = 0;
//Exit if the file does not exist
if (!file.exists()) {
return count;
}
//Recursively count children if it is a directory,If it is a file, it counts itself
if (file.isDirectory()) {
for (File child : file.listFiles()) {
count += countFile(child);
}
} else {
count = 1;
}
//Return the total
return count;
}
The above method can only count the number of files that exist under the argument object! Aside from the practicality of this method, I like recursive processing because it feels like programming.
Recommended Posts