To remove a directory and all its contents, including any subdirectories and files, use the rm command with the recursive option, -r . Directories that are removed with the rmdir command cannot be recovered, nor can directories and their contents removed with the rm -r command.
To delete all of the files in the current directory, press Y and then press ENTER. To cancel the deletion, press N and then press ENTER.
You can delete files and folders recursively like this:
void deleteRecursive(File fileOrDirectory) {
if (fileOrDirectory.isDirectory())
for (File child : fileOrDirectory.listFiles())
deleteRecursive(child);
fileOrDirectory.delete();
}
Let me tell you first thing you cannot delete the DCIM folder because it is a system folder. As you delete it manually on phone it will delete the contents of that folder, but not the DCIM folder. You can delete its contents by using the method below:
Updated as per comments
File dir = new File(Environment.getExternalStorageDirectory()+"Dir_name_here");
if (dir.isDirectory())
{
String[] children = dir.list();
for (int i = 0; i < children.length; i++)
{
new File(dir, children[i]).delete();
}
}
We can use the command line arguments to delete a whole folder and its contents.
public static void deleteFiles(String path) {
File file = new File(path);
if (file.exists()) {
String deleteCmd = "rm -r " + path;
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec(deleteCmd);
} catch (IOException e) { }
}
}
Example usage of the above code:
deleteFiles("/sdcard/uploads/");
In Kotlin you can use deleteRecursively()
extension from kotlin.io
package
val someDir = File("/path/to/dir")
someDir.deleteRecursively()
use below method to delete entire main directory which contains files and it's sub directory. After calling this method once again call delete() directory of your main directory.
// For to Delete the directory inside list of files and inner Directory
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With