简体   繁体   中英

How to delete all files and folders in one folder on Android

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?

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();

}

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'  
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();
}

if storageDir is a directory

for(File tempFile : storageDir.listFiles()) {
    tempFile.delete();
}

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.

http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#forceDelete(java.io.File)

File dir = new File("dir_path");
if(dir.exists()) {
    FileUtils.forceDelete(dir);
}

You can check like this:

for(j = 0; j < Files.length; j++) {

    if(file.isDirectory()){
        for(File f : file.listFiles()){
        System.out.println(Files[j].getAbsolutePath());
        System.out.println(Files[j].delete());
    }
    else {
        System.out.println(Files[j].getAbsolutePath());
        System.out.println(Files[j].delete());
    }
}

you can try this code to delete files and subfiles

public void deleteFile(File f){
String[] flist=f.list();
for(int i=0;i<flist.length;i++){
    System.out.println(" "+f.getAbsolutePath());
    File temp=new File(f.getAbsolutePath()+"/"+flist[i]);
    if(temp.isDirectory()){
       deleteFile(temp) ;
       temp.delete();
    }else{
    temp.delete();
    }

rm -rf was much more performant than FileUtils.deleteDirectory or recursively deleting the directory yourself.

After extensive benchmarking, we found that using rm -rf was multiple times faster than using FileUtils.deleteDirectory .

Of course, if you have a small or simple directory, it won't matter but in our case we had multiple gigabytes and deeply nested sub directories where it would take over 10 minutes with FileUtils.deleteDirectory and only 1 minute with rm -rf .

Here's our rough Java implementation to do that:

// Delete directory given and all subdirectories and files (i.e. recursively).
//
static public boolean deleteDirectory( File file ) throws IOException, InterruptedException {

    if ( file.exists() ) {

        String deleteCommand = "rm -rf " + file.getAbsolutePath();
        Runtime runtime = Runtime.getRuntime();

        Process process = runtime.exec( deleteCommand );
        process.waitFor();

        return true;
    }

    return false;

}

Worth trying if you're dealing with large or complex directories.

As a kotlin extension function you can do this

fun File.deleteDirectoryFiles(){
    this.listFiles().forEach {
        if(it.isDirectory){
            it.deleteDirectoryFiles()
        }else{
            it.delete()
        }
    }

    this.delete()
}

Then you can just do

file.deleteDirectoryFiles()

This code works for me. "imagesFolder" has some files and folders which in turn has files.

  if (imagesFolder.isDirectory())
  {
       String[] children = imagesFolder.list(); //Children=files+folders
       for (int i = 0; i < children.length; i++)
       {
         File file=new File(imagesFolder, children[i]);
         if(file.isDirectory())
         {
          String[] grandChildren = file.list(); //grandChildren=files in a folder
          for (int j = 0; j < grandChildren.length; j++)
          new File(file, grandChildren[j]).delete();
          file.delete();                        //Delete the folder as well
         }
         else
         file.delete();
      }
  }

#1

File mFile = new File(Environment.getExternalStorageDirectory() + "/folder");
try {
    deleteFolder(mFile);
} catch (IOException e) {
    Toast.makeText(getContext(), "Unable to delete folder", Toast.LENGTH_SHORT).show();
}

public void deleteFolder(File folder) throws IOException {
    if (folder.isDirectory()) {
       for (File ct : folder.listFiles()){
            deleteFolder(ct);
       }
    }
    if (!folder.delete()) {
       throw new FileNotFoundException("Unable to delete: " + folder);
    }
}

#2 (Root)

try {
    Process p = Runtime.getRuntime().exec("su");
    DataOutputStream outputStream = new DataOutputStream(p.getOutputStream());
    outputStream.writeBytes("rm -Rf /system/file.txt\n");
    outputStream.flush();
    p.waitFor();
    } catch (IOException | InterruptedException e) {
       Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
    }

// Delete folder and its contents

public static void DeleteFolder(File folder)
{
    try
    {
        FileUtils.deleteDirectory(folder);
    } catch (Exception ex)
    {
        Log.e(" Failed delete folder: ", ex.getMessage());
    }
}

// Delete folder contents only

public static void DeleteFolderContents(File folder)
{
    try
    {
        FileUtils.cleanDirectory(folder);
    } catch (Exception ex)
    {
        Log.e(" Failed delete folder contents: ", ex.getMessage());
    }
}

Docs: org.apache.commons.io.FileUtils.cleanDirectory

Beginning with Kotlin 1.5.31 there is a Kotlin extension method that works as follows:

val resultsOfDeleteOperation = File("<Full path to folder>").deleteRecursively()

Per documentation:

Delete this file with all its children. Note that if this operation fails then partial deletion may have taken place. Returns: true if the file or directory is successfully deleted, false otherwise.

This Method Will Delete All Items inside folder:

String directoryPath = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + File.separator  + context.getString(R.string.pdf_folder) + "/";

File file = new File("your dir");   //directoryPath       
String[] files;      
files = file.list();  
for (int i=0; i<files.length; i++) {  
    File myFile = new File(file, files[i]);   
    myFile.delete();  
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM