gpt4 book ai didi

android - 空目录不在android中删除

转载 作者:行者123 更新时间:2023-11-29 21:20:06 27 4
gpt4 key购买 nike

谁能说出为什么即使 path.exists() 返回 true 但不执行删除操作,此代码也无法删除空目录。

  @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File file = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/directoryName");
boolean isDeleted = deleteDirectory(file);
System.out.println(isDeleted);
}

static public boolean deleteDirectory(File path) {
if (path.exists()) {
System.out.println("MainActivity.deleteDirectory()");
File[] files = path.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
deleteDirectory(files[i]);
} else {
files[i].delete();
}
}
}
return (path.delete());
}

最佳答案

将顺序稍微更改为:

boolean deleteDirectory(File path) {
if(path.exists()) {
if (path.isDirectory()) {
File[] files = path.listFiles();
for (int i=0; i<files.length; i++) {
deleteDirectory(files[i]);
}
}
return path.delete();
}

return false;
}

并记得声明权限:

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

关于android - 空目录不在android中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20836905/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com