33

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?

lc.
  • 113,939
  • 20
  • 158
  • 187
brian
  • 6,802
  • 29
  • 83
  • 124

15 Answers15

73

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

}
Community
  • 1
  • 1
duggu
  • 37,851
  • 12
  • 116
  • 113
  • straight forward – Jaber Shabeek Jan 16 '19 at 11:29
  • 2
    `fileOrDirectory.listFiles()` may return null if there is I/O error when reading the files. This is stated in the documentation : developer.android.com/reference/java/io/File.html#listFiles() – HB. Jul 08 '19 at 05:14
44

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'  
King of Masses
  • 18,405
  • 4
  • 60
  • 77
Lesleh
  • 1,665
  • 15
  • 24
18
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();
}
Achintya Jha
  • 12,735
  • 2
  • 27
  • 39
8

if storageDir is a directory

for(File tempFile : storageDir.listFiles()) {
    tempFile.delete();
}
ergunkocak
  • 3,334
  • 1
  • 32
  • 31
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.

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);
}
Shashank
  • 325
  • 4
  • 12
  • It would be nice for you to format a code snippet within your answer, rather than simply linking a link. Also, try and explain exactly what you providing as an answer. – Zizouz212 Mar 27 '15 at 21:53
  • Don't forget to add the commons io jar to your project. [apache commons jar link is here ] (http://commons.apache.org/proper/commons-io/download_io.cgi) – Shashank Mar 30 '15 at 05:46
4

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());
    }
}
MysticMagicϡ
  • 28,593
  • 16
  • 73
  • 124
4

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();
    }
Imrank
  • 1,009
  • 5
  • 15
3

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.

Kenneth Argo
  • 1,697
  • 12
  • 19
1

// 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

Gogu CelMare
  • 699
  • 6
  • 15
1

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.

Joshua Pinter
  • 45,245
  • 23
  • 243
  • 245
1

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()
tyczj
  • 71,600
  • 54
  • 194
  • 296
0

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();
      }
  }
Kittu
  • 61
  • 9
0

#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();
    }
Lennoard Silva
  • 767
  • 1
  • 8
  • 17
0

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

Use this methods to delete folder and its sub-folders with files this is working fine.

public static void deleteFolders(File folder){
    File[] subfiles;
    if(folder.isFile()){folder.delete();}
    else
    if(folder.isDirectory()){
        if(folder.listFiles().length>=1){
            try{
                subfiles=folder.listFiles();
                for(int f = 0;f<subfiles.length;f++){
                    if(subfiles[f].isFile()){
                        deleteFolders(subfiles[f]);
                    }
                    if(subfiles[f].isDirectory()){
                        if(subfiles[f].listFiles().length>=1){
                            deleteFolders(subfiles[f]);
                        }else
                        deletes(subfiles[f]);
                    }
                }
            }
            finally {
                folder.delete();
                deleteFolders(folder);
            }
        }
    }
}
public static void deletes(File file)
{
    if (file.exists())
    {
        if (file.isDirectory() &&
            file.listFiles().length == 0)
        {
            file.delete();
        }else
        if (file.isFile())
        {
            file.delete();
        }
        else
        { 
        if(file.isDirectory()&&file.listFiles().length>=1){
            File[] files = file.listFiles();
            if (files.length >= 1)
            {
                int i;
                for (i = 0;i < files.length;i++)
                {
                    files[i].delete();
                }
                file.delete();
            }
          } 
        }
    }

hope this will help.

  • 1
    Note that code-only answers are discouraged. I suggest you add explanation, especially regarding the recursive calls to method `deleteFolders` since new programmers often have difficulty understanding how recursion works. – Abra Aug 21 '23 at 14:03