简体   繁体   English

如何删除Android上一个文件夹下的所有文件和文件夹

[英]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.它将删除 false,其中Files[j]是一个文件夹。

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?检查此链接是否从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.最简单的方法是使用 Apache Commons IO 库中的FileUtils.deleteDirectory

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在 gradle 文件中添加这一行让 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.您可以这样编写方法:删除目录下的所有文件和子目录。如果所有删除成功,则返回true。如果删除失败,该方法将停止尝试删除并返回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如果storageDir是目录

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)对于您的情况,这非常有效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) 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. rm -rf高性能FileUtils.deleteDirectory或递归删除目录自己。

After extensive benchmarking, we found that using rm -rf was multiple times faster than using FileUtils.deleteDirectory .经过广泛的基准测试,我们发现使用rm -rf比使用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 .当然,如果您有一个小目录或简单目录,这并不重要,但在我们的情况下,我们有多个 GB 和深度嵌套的子目录,其中FileUtils.deleteDirectory需要 10 多分钟,而rm -rf仅需要 1 分钟。

Here's our rough Java implementation to do that:这是我们粗略的 Java 实现:

// 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作为 kotlin 扩展功能,您可以执行此操作

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. “imagesFolder”有一些文件和文件夹,而这些文件和文件夹又包含文件。

  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 #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) #2(根)

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文档: org.apache.commons.io.FileUtils.cleanDirectory

Beginning with Kotlin 1.5.31 there is a Kotlin extension method that works as follows:从 Kotlin 1.5.31 开始,有一个 Kotlin 扩展方法,其工作方式如下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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