无法从内部存储文件夹删除文件

时间:2020-02-28 10:08:56

标签: android android-file

我要从下载文件夹中删除所有文件

enter image description here

我正在尝试这种方法-

File mydir = new File(String.valueOf(Environment.getExternalStoragePublicDirectory("Download")));
File lister = mydir.getAbsoluteFile();

System.out.println("Total files: " + lister.list().length);

for (String list : lister.list()) {
    File f = new File(lister, list);
    if (f.delete())
        System.out.println(list + " is Deleted!");
    else
        System.out.println(list + " not deleted!");
}

它不起作用,f.delete返回false。

我已经在SO上研究了许多此类问题,其中大多数建议使用delete()或getCanonicalFile()。delete()。这只是行不通。

清单-

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

3 个答案:

答案 0 :(得分:1)

尝试此操作,这将删除filePath目录下的所有文件

File file = new File(filePath);

if (file.isDirectory()) {
    String[] children = file.list();
    if (children != null) {
        for (String aChildren : children) {
            boolean isDelete = new File(file, aChildren).delete();
            if (isDelete)
                  System.out.println(aChildren + " is Deleted!");
            else
                  System.out.println(aChildren + " not deleted!");
        }
    }
}

答案 1 :(得分:1)

解决了。

我的应用仅请求用户具有读取权限,而不是WRITE。

删除任何文件都需要WRITE权限。所以我将READ改为WRITE,它起作用了!

ILogger

答案 2 :(得分:0)

不是答案,而是更强大的代码:

                            File dir = Environment.getExternalStoragePublicDirectory("Download");

                            if ( !dir.canWrite() )
                            {
                                Toast.makeText(context, "Can not write in directory\n\n"  + dir.getAbsolutePath(), Toast.LENGTH_LONG).show();

                                return;
                            }

                            File files [] = dir.listFiles();

                            if ( files==null )
                            {
                                Toast.makeText(context, "Could not listFiles() for\n\n"  + dir.getAbsolutePath(), Toast.LENGTH_LONG).show();

                                return;
                            }

                            for ( File file : files)
                            {
                                if ( file.isDirectory())
                                    continue;

                                if ( ! file.delete())
                                {
                                Toast.makeText(context, "Could not delete\n\n" + file.getAbsolutePath(), Toast.LENGTH_LONG).show();

                                break;
                                }

                            }

请尝试。