Search code examples
javaandroidfileinputstream

How do I delete a file stored in cache? (android)


I am not able delete file that is stored in cache. I am using the cache for several purposes. I am reading and writing but not able to delete. Can someone please help me with this?

//write
   public static void writeObject(Context context, String key, Object object)
                                  throws IOException {
            Log.d("Cache", "WRITE: context");
            FileOutputStream fos = context.openFileOutput(key, Context.MODE_PRIVATE);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(object);
            oos.close();
            fos.close();
   }

//read
   public static Object readObject(Context context, String key) throws IOException,
         ClassNotFoundException {
      FileInputStream fis = context.openFileInput(key);
      ObjectInputStream ois = new ObjectInputStream(fis);
      Object object = ois.readObject();
      return object;
   }

//delete
   public static void clearCahe(String key) throws IOException,ClassNotFoundException {
        File file = new File(key);
        file.delete();
   }

Solution

  • context.openFileOutput(key writes the file to internal memory. The path you can find with getFilesDir() and looks like /data/data/<yourpackagename>/files.

    So if you want to delete the file 'key' you have to set up the path for File file = new File(path) as String path = getFilesDir().getAbsolutePath() + "/" + key;.

    And use file.exists() to check if the file exists!