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

问题描述 投票:0回答:3

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

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"/>
android android-file
3个回答
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!");
        }
    }
}

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

                            }

请尝试。


0
投票

已修复。

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

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

 if (ContextCompat.checkSelfPermission(MainActivity.this
            , Manifest.permission.**WRITE**_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) 
     {   
       // ...
     }
© www.soinside.com 2019 - 2024. All rights reserved.