如何使用Android删除外部文件夹?

时间:2018-07-29 21:21:19

标签: java android file-manager

我一直在寻找它,但是我的问题没有任何答案。我正在编写一个应用程序,我想删除一个外部文件夹。例如/ storage / emulated / 0 / MyFolder,有很多方法可以从内部应用程序文件夹和外部应用程序文件夹创建和读取文件,但是我不知道如何访问“ / storage / emulated / 0”中的文件/...”。

谢谢。

2 个答案:

答案 0 :(得分:2)

  public static void deleteDir(Context ctx) {

        try {
            File myFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                                + File.separator
                                + "MyFolder");
            }
            if (myFile.exists()) {
                deleteRecursive(myFile);
            }
        }catch (Exception ignored){
            Log.e("Delete error File: %s",ignored.getMessage());
        }
    }

    private static void deleteRecursive(File myFile) {
        if (myFile.isDirectory())
            for (File child : myFile.listFiles())
                deleteRecursive(child);
        Log.e("MyFolder Files Deleted!!! : %s", myFile.delete());
    }
  • 将此行添加到应用manifest.xml

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

更新 -如Android 6+

所需的CommonsWare运行时权限请求所述
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN
            && ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(context, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 101);
    } else {
        deleteDir(context);
    }

您的活动

  @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 101:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    deleteDir(context);
                }
        }
    }

答案 1 :(得分:0)

new File("/storage/emulated/0/MyFolder").delete();

@ 您的manifest.xml

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

更新:如CommonsWare hardcoded filesystem paths might be invalid for some versions of Android所述。

new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/MyFolder").delete();