我想删除 SD 卡上的一些文件,但我没有办法..
我尝试了 File.delete()
方法,然后我尝试了 file.getCanonicalFile().delete()
还有很多 ..
我的应用程序只能删除设备存储上的文件。
我已获得 list 文件中定义的权限,如下所示。
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
我也在代码中请求许可:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
new AlertDialog.Builder(this)
.setTitle(R.string.read_storage_message)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MainActivity.READ_STORAGE_PERMISSION_ID);
}
}
)
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
AppKiller.kill();
}
}
).show();
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
new AlertDialog.Builder(this)
.setTitle(R.string.write_storage_message)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MainActivity.STORAGE_PERMISSION_ID);
}
}
)
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
AppKiller.kill();
}
}
).show();
}
}
我正在使用以下方法删除文件,但正如我之前提到的,我已经使用了在 Stack-overflow 和其他人中找到的大量解决方案。
protected boolean delete(Context context) throws Exception {
boolean delete = false;
File file = new File(Environment.getExternalStorageDirectory().getPath() + getName());
if (file.exists()) {
delete = file.delete();
if (!delete) {
delete = file.getCanonicalFile().delete();
}
if (!delete) {
String deleteCmd = "rm -r " + file.getAbsolutePath();
Runtime runtime = Runtime.getRuntime();
runtime.exec(deleteCmd);
}
}
return delete;
}
可能是因为我要求READ_EXTERNAL_STORAGE
和WRITE_EXTERNAL_STORAGE
权限,但在代码中我只是获得READ_EXTERNAL_STORAGE
授权,另一个是被 Android 忽略(在我接受第一个后,它不会显示带有允许-拒绝选项的权限 WRITE_EXTERNAL_STORAGE
弹出窗口)。难道不是因为他们在android中有相同的权限等级吗?
有什么问题吗?
最佳答案
如果你想从 SD 卡中删除文件,你可以使用下面的代码:
File file = new File("/sdcard/myfile.txt");
boolean deleted = file.delete();
关于java - 无法删除SD卡上的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51335627/