如何删除整个文件夹和内容?


185

我希望我的应用程序的用户能够删除DCIM文件夹(位于SD卡上并包含子文件夹)。

如果可能的话,这可能吗?


1
除了递归自下而上的删除方法?
Sarwar Erfan,

如果目录很大或很复杂,则应使用rm -rf directory代替FileUtils.deleteDirectory。基准测试后,我们发现它快了好几倍。在此处查看示例实现:stackoverflow.com/a/58421350/293280
Joshua Pinter

Answers:


299

让我告诉您第一件事,您不能删除DCIM文件夹,因为它是系统文件夹。在电话上手动删除它时,它将删除该文件夹的内容,但不会删除DCIM文件夹。您可以使用以下方法删除其内容:

根据评论更新

File dir = new File(Environment.getExternalStorageDirectory()+"Dir_name_here"); 
if (dir.isDirectory()) 
{
    String[] children = dir.list();
    for (int i = 0; i < children.length; i++)
    {
       new File(dir, children[i]).delete();
    }
}

3
erm我如何声明目录是什么?
新手

即时通讯基本上试图删除所有照片,以便并不重要是DCIM不会被删除,只要照片是...所以即使删除100MEDIA的文件夹内,这将做的工作
新手

1
您必须使用dicm文件夹的路径声明目录:use file r = file(path);
chikka.anddev 2011年

3
使用的文件目录=新文件(Environment.getExternalStorageDirectory()+“ / DCIM / 100MEDIA”);
新手

1
@chiragshah删除文件夹并重新创建文件夹后,将创建一个与提到的文件夹名称相同的未知文件。如果我尝试访问该文件,则会引发异常,例如资源或设备繁忙。我还检查了我找到MD5签名的
2012年

529

您可以像这样递归删除文件和文件夹:

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

    fileOrDirectory.delete();
}

21
我没有进行效率测试,但我相信我的功能更强大。chirag适用于DCIM文件夹的特定情况,其中DCIM内的文件夹应仅包含文件(即DCIM内的文件夹通常不包含任何子文件夹)。我的版本将删除嵌套到任何深度的文件夹。用户可能已经修改了SD卡的内容,因此DCIM包含嵌套得更深的文件夹(例如DCIM\foo\bar\pic.jpg),在这种情况下,chirag的代码将失败。
teedyay'8

2
一位同事问我一个问题:如果文件夹本身具有符号链接,而您执行此代码段,会发生什么情况?
p4u144

1
@ p4u144给您的同事一个成为天才的高五!发现得好!老实说,我不知道这段代码是否会尊重并遵循符号链接,但是如果这样做的话,您将陷入无限循环。你喜欢测试吗?
teedyay

8
@ p4u144不用担心符号链接。“对于符号链接,链接将被删除,而不是链接的目标。” 来自docs.oracle.com/javase/tutorial/essential/io/delete.html
corbin 2015年

3
此处fileOrDirectory.listFiles()可能null存在NPE:如果在读取文件时出现I / O错误,则可能会返回NPE 。这在文档中有明确说明:developer.android.com/reference/java/io/File.html#listFiles()
Brian Yencho

67

我们可以使用命令行参数来删除整个文件夹及其内容。

public static void deleteFiles(String path) {

    File file = new File(path);

    if (file.exists()) {
        String deleteCmd = "rm -r " + path;
        Runtime runtime = Runtime.getRuntime();
        try {
            runtime.exec(deleteCmd);
        } catch (IOException e) { }
    }
}

上面代码的示例用法:

deleteFiles("/sdcard/uploads/");

2
看起来不错,您知道这是同步还是异步?文档不说:developer.android.com/reference/java/lang/...
有人的地方

2
馊主意。为什么要放在外壳上?
noamtm '16


33

在Kotlin中,您可以使用deleteRecursively()扩展kotlin.io

val someDir = File("/path/to/dir")
someDir.deleteRecursively()

2
在Java中,FilesKt.deleteRecursively(new File("/path/to/dir"));如果您使用的是kotlin-stdlib,则可以使用
Joonsoo,

此命令将删除内部包含内容的“ / dir”目录,或仅删除“ / dir”目录中的内容,并且目录仍保留在其中?
Bhimbim

1
@Bhimbim lemme google docs为您“删除此文件及其所有子项。”。因此,目录以及内容将被删除
Dima Rostopira

谢谢@DimaRostopira!。
Bhimbim

科特林来营救!
Tobi Oyelekan

15

使用以下方法删除包含文件及其子目录的整个主目录。再次调用此方法后,请调用主目录的delete()目录。

// For to Delete the directory inside list of files and inner Directory
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();
}

在所有答案中,这是唯一的真实答案,它也会在删除目录中的文件后也删除该目录。
zeeshan 2015年

文件文件=新文件(Environment.getExternalStorageDirectory()+分隔符+“ folder_name” +分隔符);deleteDir(file);是的。谢谢:)
ashishdhiman2007

14

对于仅包含文件的文件夹,您的方法很不错,但是如果您要查找还包含子文件夹的方案,则需要递归

另外,您应该捕获退货的退货价值,以确保允许您删除文件

并包括

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

在你的清单上

void DeleteRecursive(File dir)
{
    Log.d("DeleteRecursive", "DELETEPREVIOUS TOP" + dir.getPath());
    if (dir.isDirectory())
    {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++)
        {
            File temp = new File(dir, children[i]);
            if (temp.isDirectory())
            {
                Log.d("DeleteRecursive", "Recursive Call" + temp.getPath());
                DeleteRecursive(temp);
            }
            else
            {
                Log.d("DeleteRecursive", "Delete File" + temp.getPath());
                boolean b = temp.delete();
                if (b == false)
                {
                    Log.d("DeleteRecursive", "DELETE FAIL");
                }
            }
        }

    }
    dir.delete();
}

5
如果用于(File currentFile:file.listFiles()){
Thorben

8

有很多答案,但是我决定添加自己的答案,因为两者几乎没有什么不同。它基于OOP;)

我创建了DirectoryCleaner类,每次需要清理某个目录时都会提供帮助。

public class DirectoryCleaner {
    private final File mFile;

    public DirectoryCleaner(File file) {
        mFile = file;
    }

    public void clean() {
        if (null == mFile || !mFile.exists() || !mFile.isDirectory()) return;
        for (File file : mFile.listFiles()) {
            delete(file);
        }
    }

    private void delete(File file) {
        if (file.isDirectory()) {
            for (File child : file.listFiles()) {
                delete(child);
            }
        }
        file.delete();

    }
}

它可以用于解决以下问题:

File dir = new File(Environment.getExternalStorageDirectory(), "your_directory_name");
new DirectoryCleaner(dir).clean();
dir.delete();

7

如果您不需要递归删除内容,可以尝试如下操作:

File file = new File(context.getExternalFilesDir(null), "");
    if (file != null && file.isDirectory()) {
        File[] files = file.listFiles();
        if(files != null) {
            for(File f : files) {   
                f.delete();
            }
        }
    }

6

如果目录具有Java中的子目录或文件,则无法删除该目录。试试这个两行简单的解决方案。这将删除目录并在目录内进行比赛。

File dirName = new File("directory path");
FileUtils.deleteDirectory(dirName);

在gradle文件中添加此行并同步项目

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

作为2班轮,这很简单。但是安装整个库以仅利用其一种方法似乎效率低下。使用这种替代
本Kathir

gradle插入尖端挽救了我的生命。
Dracarys

5
public static void deleteDirectory( File dir )
{

    if ( dir.isDirectory() )
    {
        String [] children = dir.list();
        for ( int i = 0 ; i < children.length ; i ++ )
        {
         File child =    new File( dir , children[i] );
         if(child.isDirectory()){
             deleteDirectory( child );
             child.delete();
         }else{
             child.delete();

         }
        }
        dir.delete();
    }
}

5

参见android.os.FileUtils,它隐藏在API 21上

public static boolean deleteContents(File dir) {
    File[] files = dir.listFiles();
    boolean success = true;
    if (files != null) {
        for (File file : files) {
            if (file.isDirectory()) {
                success &= deleteContents(file);
            }
            if (!file.delete()) {
                Log.w("Failed to delete " + file);
                success = false;
            }
        }
    }
    return success;
}

来源:https//android.googlesource.com/platform/frameworks/base/+/master/core/java/android/os/FileUtils.java#414


4

根据文档

如果此抽象路径名不表示目录,则此方法返回null。

因此,您应该检查是否listFiles存在null,如果没有则继续

boolean deleteDirectory(File path) {
    if(path.exists()) {
        File[] files = path.listFiles();
        if (files == null) {
            return false;
        }
        for (File file : files) {
            if (file.isDirectory()) {
                deleteDirectory(file);
            } else {
                boolean wasSuccessful = file.delete();
                if (wasSuccessful) {
                    Log.i("Deleted ", "successfully");
                }
            }
        }
    }
    return(path.delete());
}

1
这应该是公认的答案。奇迹般有效!
MSeiz5 '19

3

这就是我所做的...(简短且经过测试)

    ...
    deleteDir(new File(dir_to_be_deleted));
    ...

    // delete directory and contents
    void deleteDir(File file) { 
        if (file.isDirectory())
            for (String child : file.list())
                deleteDir(new File(file, child));
        file.delete();  // delete child file or empty directory
    }

3
private static void deleteRecursive(File dir)
{
    //Log.d("DeleteRecursive", "DELETEPREVIOUS TOP" + dir.getPath());
    if (dir.isDirectory())
    {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++)
        {
            File temp = new File(dir, children[i]);
            deleteRecursive(temp);
        }

    }

    if (dir.delete() == false)
    {
        Log.d("DeleteRecursive", "DELETE FAIL");
    }
}

2

从目录删除所有文件的简单方法:

它是通过仅调用从目录中删除所有图像的通用功能

deleteAllImageFile(context);

public static void deleteAllFile(Context context) {
File directory = context.getExternalFilesDir(null);
        if (directory.isDirectory()) {
            for (String fileName: file.list()) {
                new File(file,fileName).delete();
            }
        }    
    } 

2

我知道的最安全的代码:

private boolean recursiveRemove(File file) {
    if(file == null  || !file.exists()) {
        return false;
    }

    if(file.isDirectory()) {
        File[] list = file.listFiles();

        if(list != null) {

            for(File item : list) {
                recursiveRemove(item);
            }

        }
    }

    if(file.exists()) {
        file.delete();
    }

    return !file.exists();
}

检查文件是否存在,处理空值,检查目录是否实际删除


1

这是一个非递归的实现,只是为了好玩:

/**
 * Deletes the given folder and all its files / subfolders.
 * Is not implemented in a recursive way. The "Recursively" in the name stems from the filesystem command
 * @param root The folder to delete recursively
 */
public static void deleteRecursively(final File root) {
    LinkedList<File> deletionQueue = new LinkedList<>();
    deletionQueue.add(root);

    while(!deletionQueue.isEmpty()) {
        final File toDelete = deletionQueue.removeFirst();
        final File[] children = toDelete.listFiles();
        if(children == null || children.length == 0) {
            // This is either a file or an empty directory -> deletion possible
            toDelete.delete();
        } else {
            // Add the children before the folder because they have to be deleted first
            deletionQueue.addAll(Arrays.asList(children));
            // Add the folder again because we can't delete it yet.
            deletionQueue.addLast(toDelete);
        }
    }
}

1

短版科尔特丁版

fun File.deleteDirectory(): Boolean {
    return if (exists()) {
        listFiles()?.forEach {
            if (it.isDirectory) {
                it.deleteDirectory()
            } else {
                it.delete()
            }
        }
        delete()
    } else false
}

1

(尝试删除所有子文件和子目录,包括提供的目录)

  1. 如果File删除
  2. 如果Empty Directory删除
  3. 如果Not Empty Directory,使用子目录再次调用delete,则重复1到3

例:

File externalDir = Environment.getExternalStorageDirectory()
Utils.deleteAll(externalDir); //BE CAREFUL.. Will try and delete ALL external storage files and directories

要访问外部存储目录,您需要以下权限:

(使用ContextCompat.checkSelfPermissionActivityCompat.requestPermissions

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

递归方法:

public static boolean deleteAll(File file) {
    if (file == null || !file.exists()) return false;

    boolean success = true;
    if (file.isDirectory()) {
        File[] files = file.listFiles();
        if (files != null && files.length > 0) {
            for (File f : files) {
                if (f.isDirectory()) {
                    success &= deleteAll(f);
                }
                if (!f.delete()) {
                    Log.w("deleteAll", "Failed to delete " + f);
                    success = false;
                }
            }
        } else {
            if (!file.delete()) {
                Log.w("deleteAll", "Failed to delete " + file);
                success = false;
            }
        }
    } else {
        if (!file.delete()) {
            Log.w("deleteAll", "Failed to delete " + file);
            success = false;
        }
    }
    return success;
}

0

我已经尽力将它删除具有任何目录结构的文件夹。

public int removeDirectory(final File folder) {

    if(folder.isDirectory() == true) {
        File[] folderContents = folder.listFiles();
        int deletedFiles = 0;

        if(folderContents.length == 0) {
            if(folder.delete()) {
                deletedFiles++;
                return deletedFiles;
            }
        }
        else if(folderContents.length > 0) {

            do {

                File lastFolder = folder;
                File[] lastFolderContents = lastFolder.listFiles();

                //This while loop finds the deepest path that does not contain any other folders
                do {

                    for(File file : lastFolderContents) {

                        if(file.isDirectory()) {
                            lastFolder = file;
                            lastFolderContents = file.listFiles();
                            break;
                        }
                        else {

                            if(file.delete()) {
                                deletedFiles++;
                            }
                            else {
                                break;
                            }

                        }//End if(file.isDirectory())

                    }//End for(File file : folderContents)

                } while(lastFolder.delete() == false);

                deletedFiles++;
                if(folder.exists() == false) {return deletedFiles;}

            } while(folder.exists());
        }
    }
    else {
        return -1;
    }

    return 0;

}

希望这可以帮助。


0
//To delete all the files of a specific folder & subfolder
public static void deleteFiles(File directory, Context c) {
    try {
        for (File file : directory.listFiles()) {
            if (file.isFile()) {
                final ContentResolver contentResolver = c.getContentResolver();
                String canonicalPath;
                try {
                    canonicalPath = file.getCanonicalPath();
                } catch (IOException e) {
                    canonicalPath = file.getAbsolutePath();
                }
                final Uri uri = MediaStore.Files.getContentUri("external");
                final int result = contentResolver.delete(uri,
                        MediaStore.Files.FileColumns.DATA + "=?", new String[]{canonicalPath});
                if (result == 0) {
                    final String absolutePath = file.getAbsolutePath();
                    if (!absolutePath.equals(canonicalPath)) {
                        contentResolver.delete(uri,
                                MediaStore.Files.FileColumns.DATA + "=?", new String[]{absolutePath});
                    }
                }
                if (file.exists()) {
                    file.delete();
                    if (file.exists()) {
                        try {
                            file.getCanonicalFile().delete();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        if (file.exists()) {
                            c.deleteFile(file.getName());
                        }
                    }
                }
            } else
                deleteFiles(file, c);
        }
    } catch (Exception e) {
    }
}

这是您的解决方案,它也会刷新图库。


0

解决它的另一种(现代)方法。

public class FileUtils {
    public static void delete(File fileOrDirectory) {
        if(fileOrDirectory != null && fileOrDirectory.exists()) {
            if(fileOrDirectory.isDirectory() && fileOrDirectory.listFiles() != null) {      
                Arrays.stream(fileOrDirectory.listFiles())
                      .forEach(FileUtils::delete);
            }
            fileOrDirectory.delete();
        }
    }
}

从API 26开始在Android上

public class FileUtils {

    public static void delete(File fileOrDirectory)  {
        if(fileOrDirectory != null) {
            delete(fileOrDirectory.toPath());
        }
    }

    public static void delete(Path path)  {
        try {
            if(Files.exists(path)) {
                Files.walk(path)
                        .sorted(Comparator.reverseOrder())
                        .map(Path::toFile)
//                      .peek(System.out::println)
                        .forEach(File::delete);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.