brian
brian

Reputation: 6912

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?

Upvotes: 34

Views: 77659

Answers (16)

Mohammad Aqeel Abdo
Mohammad Aqeel Abdo

Reputation: 11

if you are using Kotlin then

dirToDelete.deleteRecursively()

will delete the folder and all its children recursively even if the child is a folder.

but in case you want to delete the children only you may loop over the children this way

dirToDeleteChildrenOnly.listFiles().forEach {fileOrFolder->
    fileOrFolder.deleteRecursively()
}

Upvotes: 0

Cripple Sd
Cripple Sd

Reputation: 11

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.

Upvotes: 0

Fayyaz kharl
Fayyaz kharl

Reputation: 53

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

Upvotes: 0

Kenneth Argo
Kenneth Argo

Reputation: 1767

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.

Upvotes: 4

tyczj
tyczj

Reputation: 73731

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

Upvotes: 1

Joshua Pinter
Joshua Pinter

Reputation: 47471

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.

Upvotes: 1

duggu
duggu

Reputation: 38409

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

}

Upvotes: 75

Gogu CelMare
Gogu CelMare

Reputation: 815

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

Upvotes: 1

Lennoard Silva
Lennoard Silva

Reputation: 935

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

Upvotes: 0

Lesleh
Lesleh

Reputation: 1675

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'  

Upvotes: 44

ergunkocak
ergunkocak

Reputation: 3380

if storageDir is a directory

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

Upvotes: 8

Kittu
Kittu

Reputation: 61

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

Upvotes: 0

Shashank
Shashank

Reputation: 335

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

Upvotes: 5

Achintya Jha
Achintya Jha

Reputation: 12843

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

Upvotes: 18

Imrank
Imrank

Reputation: 1019

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

Upvotes: 4

MysticMagicϡ
MysticMagicϡ

Reputation: 28823

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

Upvotes: 4

Related Questions