[英]Deleting folders quickly on android
我有一個需要能夠快速刪除大目錄的 android 應用程序。 我知道當應用程序有大量數據時,操作系統能夠立即清除數據應用程序(從應用程序設置)。 但是,當我手動嘗試刪除具有后台任務的目錄時,循環瀏覽文件夾並刪除文件需要很長時間(幾分鍾)才能完成。 操作系統怎么會這么快地刪除數據,但是在代碼中完成時,卻需要這么長的時間? 有更快的方法嗎?
private boolean deleteDirectory(String dir) {
Log.d(TAG, "deleteDirectory");
// If dir is not separated from the end of the character to the file, the file is automatically added delimiter
if (!dir.endsWith(File.separator))
dir = dir + File.separator;
File dirFile = new File(dir);
// If dir corresponding file does not exist or is not a directory, then exit
if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
return false;
}
boolean flag = true;
// delete all the files in the folder, including subdirectories
File[] files = dirFile.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
final int count = i;
// delete subfolders
if (files[i].isFile()) {
try {
FileUtils.forceDelete(files[count]);
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
} else if (files[i].isDirectory()) {
flag = deleteDirectory(files[i]
.getAbsolutePath());
}
if (dir == path) {
Log.d(TAG, "delete dir: " + dirFile);
curPosi++;
publishProgress(curPosi);
}
}
}
if (!flag) {
return false;
}
// delete the current directory
if (dirFile.delete()) {
return true;
} else {
return false;
}
}
我很確定操作系統通過訪問實際的文件系統在較低級別將其刪除。 無論哪種方式,您都應該嘗試使用Apache Commons FileUtils庫——它有一個deleteDirectory()
方法,可以為您節省大量遞歸。
或者,您實際上可以嘗試使用runtime.exec()
直接運行“rm -rf”,但我不確定它需要的權限。 這是一個例子
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.