我希望我的应用程序的用户能够删除DCIM文件夹(它位于SD卡上并包含子文件夹)。
这可能吗?如果可能,怎么可能?
我希望我的应用程序的用户能够删除DCIM文件夹(它位于SD卡上并包含子文件夹)。
这可能吗?如果可能,怎么可能?
当前回答
这就是我的工作…(简洁且经过测试)
...
deleteDir(new File(dir_to_be_deleted));
...
// delete directory and contents
void deleteDir(File file) {
if (file.isDirectory())
for (String child : file.list())
deleteDir(new File(file, child));
file.delete(); // delete child file or empty directory
}
其他回答
使用以下方法删除包含文件的整个主目录及其子目录。再次调用此方法后,调用主目录的delete()目录。
// For to Delete the directory inside list of files and inner Directory
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}
这种方法适用于只包含文件的文件夹,但如果您正在寻找还包含子文件夹的场景,则需要递归
此外,您应该捕获返回的返回值,以确保允许您删除该文件
,包括
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
在你的清单上
void DeleteRecursive(File dir)
{
Log.d("DeleteRecursive", "DELETEPREVIOUS TOP" + dir.getPath());
if (dir.isDirectory())
{
String[] children = dir.list();
for (int i = 0; i < children.length; i++)
{
File temp = new File(dir, children[i]);
if (temp.isDirectory())
{
Log.d("DeleteRecursive", "Recursive Call" + temp.getPath());
DeleteRecursive(temp);
}
else
{
Log.d("DeleteRecursive", "Delete File" + temp.getPath());
boolean b = temp.delete();
if (b == false)
{
Log.d("DeleteRecursive", "DELETE FAIL");
}
}
}
}
dir.delete();
}
这里是一个非递归的实现,只是为了好玩:
/**
* Deletes the given folder and all its files / subfolders.
* Is not implemented in a recursive way. The "Recursively" in the name stems from the filesystem command
* @param root The folder to delete recursively
*/
public static void deleteRecursively(final File root) {
LinkedList<File> deletionQueue = new LinkedList<>();
deletionQueue.add(root);
while(!deletionQueue.isEmpty()) {
final File toDelete = deletionQueue.removeFirst();
final File[] children = toDelete.listFiles();
if(children == null || children.length == 0) {
// This is either a file or an empty directory -> deletion possible
toDelete.delete();
} else {
// Add the children before the folder because they have to be deleted first
deletionQueue.addAll(Arrays.asList(children));
// Add the folder again because we can't delete it yet.
deletionQueue.addLast(toDelete);
}
}
}
从目录中删除所有文件的简单方法:
它是一个通用函数,用于删除目录中的所有图像
deleteAllImageFile(背景);
public static void deleteAllFile(Context context) {
File directory = context.getExternalFilesDir(null);
if (directory.isDirectory()) {
for (String fileName: file.list()) {
new File(file,fileName).delete();
}
}
}
你可以像这样递归地删除文件和文件夹:
void deleteRecursive(File fileOrDirectory) {
if (fileOrDirectory.isDirectory())
for (File child : fileOrDirectory.listFiles())
deleteRecursive(child);
fileOrDirectory.delete();
}