javaandroidcachingfile-handlingmobile-development

How can I clear cache when I open my app if cache isn't empty in java?


I want to clear my app's cache when every time my app opens (something like in the onCreate) by checking if the cache directory is not empty. Is there any method to check if the cache is not empty, and then delete?


Solution

  • You don't need to check if the cache is empty. If its already empty, nothing will happen. Here is a simple function to delete all subdirectories and files:

    public static void deleteFilesFrom(String path) {
        File dir = new File(path);
        if (dir.isDirectory()) {
            File[] files = dir.listFiles();
            if (files != null) {
                for (File file : files) {
                    deleteRecursive(file);
                }
            }
        }
    }
    public static void deleteRecursive(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files != null) {
                for (File child : files) {
                    deleteRecursive(child);
                }
            }
        }
        file.delete();
    }
    

    Declare them inside onCreate

        String cacheDirPath = getCacheDir().getPath();
        deleteCacheDirContents(cacheDirPath);