How to delete all files and folders in one folder on Android
Solution 1
Simplest way would be to use FileUtils.deleteDirectory from the Apache Commons IO library.
File dir = new File("root path");
FileUtils.deleteDirectory(dir);
Bear in mind this will also delete the containing directory.
Add this line in gradle file to have Apache
compile 'org.apache.commons:commons-io:1.3.2'
Solution 2
Check this link also Delete folder from internal storage in android?.
void deleteRecursive(File fileOrDirectory) {
if (fileOrDirectory.isDirectory())
for (File child : fileOrDirectory.listFiles())
deleteRecursive(child);
fileOrDirectory.delete();
}
Solution 3
File file = new File("C:\\A\\B");
String[] myFiles;
myFiles = file.list();
for (int i=0; i<myFiles.length; i++) {
File myFile = new File(file, myFiles[i]);
myFile.delete();
}
B.delete();// deleting directory.
You can write method like this way :Deletes all files and subdirectories under dir.Returns true if all deletions were successful.If a deletion fails, the method stops attempting to delete and returns false.
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}
Solution 4
if storageDir is a directory
for(File tempFile : storageDir.listFiles()) {
tempFile.delete();
}
Solution 5
For your case, this works perfectly http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#cleanDirectory(java.io.File)
File dir = new File("dir_path");
if(dir.exists() && dir.isDirectory()) {
FileUtils.cleanDirectory(dir);
}
If you wanna delete the folder itself. (It does not have to be empty). Can be used for files too.
File dir = new File("dir_path");
if(dir.exists()) {
FileUtils.forceDelete(dir);
}
brian
Updated on November 04, 2021Comments
-
brian over 2 years
I use this code to delete all files:
File root = new File("root path"); File[] Files = root.listFiles(); if(Files != null) { int j; for(j = 0; j < Files.length; j++) { System.out.println(Files[j].getAbsolutePath()); System.out.println(Files[j].delete()); } }
It will delete false where
Files[j]
is a folder.I want to delete folder and all its sub files.
How can I modify this?