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

前端 未结 12 1025
广开言路
广开言路 2021-01-30 17:52

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


        
相关标签:
12条回答
  • 2021-01-30 18:13

    if storageDir is a directory

    for(File tempFile : storageDir.listFiles()) {
        tempFile.delete();
    }
    
    0 讨论(0)
  • 2021-01-30 18:13

    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());
        }
    }
    
    0 讨论(0)
  • 2021-01-30 18:14

    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'  
    
    0 讨论(0)
  • 2021-01-30 18:15

    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();
        }
    
    0 讨论(0)
  • 2021-01-30 18:16

    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()
    
    0 讨论(0)
  • 2021-01-30 18:18

    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);
    }
    
    0 讨论(0)
提交回复
热议问题