我一直在寻找它,但没有任何答案可以解决我的问题。我正在编写一个应用程序,我想删除一个外部文件夹。例如 /storage/emulated/0/MyFolder,有很多方法可以从内部应用程序文件夹和外部应用程序文件夹创建和读取文件,但我不知道如何访问“/storage/emulated/0”中的文件/...”。
谢谢。
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" />
更新 - 正如CommonsWare所提到的,
Android 6+
需要运行时权限请求
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);
}
}
}
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();
公共静态无效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());
}