33

我使用此代码删除所有文件:

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

它将删除 false where Files[j]is a folder。

我想删除文件夹及其所有子文件。
我该如何修改这个?

4

13 回答 13

72

检查此链接是否也从 android 的内部存储中删除文件夹?.

void deleteRecursive(File fileOrDirectory) {

    if (fileOrDirectory.isDirectory())
        for (File child : fileOrDirectory.listFiles())
            deleteRecursive(child);

    fileOrDirectory.delete();

}
于 2013-02-18T06:57:57.113 回答
43

最简单的方法是使用Apache Commons IO 库中的FileUtils.deleteDirectory

File dir = new File("root path");
FileUtils.deleteDirectory(dir);

请记住,这也会删除包含目录。

在 gradle 文件中添加这一行以获得 Apache

compile 'org.apache.commons:commons-io:1.3.2'  
于 2013-02-18T06:54:42.303 回答
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.

您可以这样编写方法:删除dir下的所有文件和子目录。如果所有删除都成功,则返回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();
}
于 2013-02-18T07:03:02.523 回答
7

如果storageDir是目录

for(File tempFile : storageDir.listFiles()) {
    tempFile.delete();
}
于 2016-04-25T12:56:00.170 回答
5

对于您的情况,这非常有效 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);
}

如果你想删除文件夹本身。(它不必为空)。也可以用于文件。

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);
}
于 2015-03-27T21:25:56.807 回答
4

你可以这样检查:

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());
    }
}
于 2013-02-18T06:56:09.863 回答
4

您可以尝试使用此代码删除文件和子文件

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();
    }
于 2013-02-18T07:00:09.373 回答
1

rm -rf比自己递归删除目录的性能要高得多FileUtils.deleteDirectory

经过广泛的基准测试,我们发现 usingrm -rf比 using 快几倍FileUtils.deleteDirectory

当然,如果您有一个小的或简单的目录,那没关系,但在我们的例子中,我们有多个千兆字节和深度嵌套的子目录,FileUtils.deleteDirectory使用rm -rf.

这是我们的粗略 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;

}

如果您正在处理大型或复杂的目录,则值得尝试。

于 2019-10-16T20:37:51.650 回答
1

作为 kotlin 扩展功能,您可以执行此操作

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

    this.delete()
}

然后你可以做

file.deleteDirectoryFiles()
于 2020-12-08T17:08:13.177 回答
1

从 Kotlin 1.5.31 开始,有一个 Kotlin 扩展方法,其工作方式如下:

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

根据文档:

删除该文件及其所有子文件。请注意,如果此操作失败,则可能已发生部分删除。返回:如果文件或目录被成功删除,则返回 true,否则返回 false。

于 2021-11-04T03:46:28.453 回答
0

这段代码对我有用。“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();
      }
  }
于 2015-09-30T16:15:22.517 回答
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(根)

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();
    }
于 2017-03-18T16:50:37.960 回答
0

// 删除文件夹及其内容

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

// 只删除文件夹内容

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

文档:org.apache.commons.io.FileUtils.cleanDirectory

于 2017-12-11T00:10:28.570 回答