我正在盯着一个用于组织和清理手机的Android应用程序,我开始做的第一件事是“空文件夹清洁工”,我认为这很容易,实际上它很容易,但我想要更进一步......
Ccleaner,例如,只搜索空文件夹,这意味着如果有一个文件夹里面只有一个空文件夹,你需要使用它2次,因为包含空文件夹的文件夹将在之后为空干净,我的代码我检查文件夹里面是否只有空文件夹,它适用于简单的情况,比如里面有两个空文件夹的文件夹,但是当它更深,它不能正常工作。
我想知道文件夹是否为空,以及文件夹是否可以安全删除,因为它只有空文件夹。
如果我在输出中有一个文件夹的文件夹就是这个:
Empty Folder: /storage/emulated/0/Folder1/Folder2
Folder safe to remove (only empty folders inside):/storage/emulated/0/Folder1
但有3 ...
Empty Folder: /storage/emulated/0/Folder1/Folder2/Folder3
Folder safe to remove (only empty folders inside): /storage/emulated/0/Folder1/Folder2
忽略第一个(Folder1
)
以下是方法:
private void getAllEmptyFoldersOfDir(File directory) {
//Log.d(TAG, "Folder: " + directory.getAbsolutePath() + "\n");
int emptyFoldersCount = 0;
final File[] files = directory.listFiles();
if (files != null) {
for (File file : files) {
if (file != null) {
if (file.getName().equals("Android") && file.isDirectory()) {
//We need to exclude this folder
continue;
}
if (file.isDirectory()) {
if (file.listFiles().length > 0) {
getAllEmptyFoldersOfDir(file);
continue;
}
emptyFoldersCount++;
Log.d(TAG, "Empty Folder: " + file.getAbsolutePath() + "\n");
}
}
}
if (files.length == emptyFoldersCount)
Log.d(TAG, "Folder safe to remove (only empty folders inside): " + directory.getAbsolutePath() + "\n");
}
}
感谢任何帮助,我的英语不好,所以任何编辑也是如此!
答案 0 :(得分:1)
这就是我提出的:
boolean getAllEmptyFoldersOfDir(File current){
if(current.isDirectory()){
File[] files = current.listFiles();
if(files.length == 0){ //There is no file in this folder - safe to delete
System.out.println("Safe to delete - empty folder: " + current.getAbsolutePath());
return true;
} else {
int totalFolderCount = 0;
int emptyFolderCount = 0;
for(File f : files){
if(f.isDirectory()){
totalFolderCount++;
if(getAllEmptyFoldersOfDir(f)){ //safe to delete
emptyFolderCount++;
}
}
}
if(totalFolderCount == files.length && emptyFolderCount == totalFolderCount){ //only if all folders are safe to delete then this folder is also safe to delete
System.out.println("Safe to delete - all subfolders are empty: " + current.getAbsolutePath());
return true;
}
}
}
return false;
}
每当文件夹可以安全删除时,此方法返回true。因此,每当您执行递归调用时,首先扫描所有子文件夹并验证它们是否为空。仅当所有子文件夹都为空(emptyFolderCount == totalFolderCount
)时,文件夹本身才能安全删除。
答案 1 :(得分:0)
除了尼克十个温恩的答案, 这是代码,如何使用他的方法删除文件:
private void deleteEmptyFolders(File pathToClear){
File file = getExternalFilesDir(null);
File[] files = file.listFiles();
for(File f : files){
if(f.isDirectory())
if(getAllEmptyFoldersOfDir(f))
if(f.delete())
Log.w("DELETED FOLDER (EMPTY)", f.getPath());
}
}