Java 如何在Android上删除一个文件夹中的所有文件和文件夹

Java 如何在Android上删除一个文件夹中的所有文件和文件夹,java,android,file-io,Java,Android,File Io,我使用此代码删除所有文件: 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].de

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

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());
    }
}
File root=新文件(“根路径”);
File[]Files=root.listFiles();
如果(文件!=null){
int j;
对于(j=0;j
文件[j]
是文件夹时,它将删除false

我想删除文件夹及其所有子文件。

我如何修改这个

最简单的方法是使用Apache Commons IO库

File dir = new File("root path");
FileUtils.deleteDirectory(dir);
请记住,这也将删除包含的目录

在gradle文件中添加这一行以使用Apache

compile 'org.apache.commons:commons-io:1.3.2'  

您可以这样检查:

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());
    }
}
for(j=0;j
同时检查此链接


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

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();
    }
public void deleteFile(文件f){
字符串[]flist=f.list();
对于(int i=0;i
File File File=新文件(“C:\\A\\B”);
字符串[]myFiles;
myFiles=file.list();

对于(inti=0;i对于您的情况,这非常有效

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

这段代码适合我。“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();
      }
  }
if(imagesFolder.isDirectory())
{
String[]children=imagesFolder.list();//children=文件+文件夹
for(int i=0;i
如果storageDir是一个目录

for(File tempFile : storageDir.listFiles()) {
    tempFile.delete();
}
#1 #2(根)
//删除文件夹及其内容

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

rm-rf
FileUtils.deleteDirectory
或自己递归删除目录更有效。 经过广泛的基准测试,我们发现使用
rm-rf
比使用
FileUtils.deleteDirectory
快数倍

当然,如果你有一个小的或简单的目录,这无关紧要,但在我们的例子中,我们有多个千兆字节和深度嵌套的子目录,使用
FileUtils.deleteDirectory
需要10分钟,而使用
rm-rf
只需要1分钟

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

}

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

作为kotlin扩展函数,您可以这样做

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

    this.delete()
}
那你就做吧

file.deleteDirectoryFiles()

可能重复:最好在答案中格式化代码段,而不是简单地链接链接。此外,请尝试准确解释您作为答案提供的内容。不要忘记将commons io jar添加到项目中。[apache commons jar链接在此]()为gradle Importt编译'org.apache.commons:commons io:1.3.2'//如果目录中有任何非空目录要删除,则此操作无效。直接
fileOrDirectory.listFiles()如果读取文件时出现I/O错误,则
可能会返回null。这在以下文档中有说明:developer.android.com/reference/java/io/File.html#listFiles()
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);
    }
}
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();
    }
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());
    }
}
// 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;

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

    this.delete()
}
file.deleteDirectoryFiles()