如何删除app的cache-folder?

saf*_*ari 12 android caching file

我阅读了缓存的Android文档(请参阅数据存储文档),但我没有得到如何清理整个文件夹.

那么如何删除我的应用程序的缓存文件夹?它在这条道路上:

/Android/data/de.stepforward/cache/

Chi*_*rag 28

将此代码放在onDestroy()中以清除应用程序缓存:

void onDestroy() { super.onDestroy();

    try {
        trimCache(this);
       // Toast.makeText(this,"onDestroy " ,Toast.LENGTH_LONG).show();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

public static void trimCache(Context context) {
    try {
       File dir = context.getCacheDir();
       if (dir != null && dir.isDirectory()) {
          deleteDir(dir);
       }
    } catch (Exception e) {
       // TODO: handle exception
    }
 }

 public static boolean deleteDir(File dir) {
    if (dir != null && 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();
 }
Run Code Online (Sandbox Code Playgroud)


net*_*ein 12

您可以使用此处引用的代码:

/sf/answers/532018021/

File cacheDir = context.getCacheDir();

File[] files = cacheDir.listFiles();

if (files != null) {
    for (File file : files)
       file.delete();
}
Run Code Online (Sandbox Code Playgroud)


Moh*_*led 9

科特林:

您也可以使用File.deleteRecursively()标准库来删除所有子目录

要删除应用程序的整个缓存目录:

context.cacheDir.deleteRecursively()
Run Code Online (Sandbox Code Playgroud)

删除缓存中的特定目录及其子目录

File(context.cacheDir, "child directory name").deleteRecursively()
Run Code Online (Sandbox Code Playgroud)

感谢您的建议@elyeante