【问题标题】:How do I delete a file stored in cache? (android)如何删除存储在缓存中的文件? (安卓)
【发布时间】:2015-04-27 10:34:06
【问题描述】:

我无法删除存储在缓存中的文件。我将缓存用于多种目的。我正在阅读和写作,但无法删除。有人可以帮我解决这个问题吗?

//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();
   }

【问题讨论】:

  • 请记录删除方法的返回类型。请打印堆栈跟踪可能是特定文件不可用。

标签: java android fileinputstream


【解决方案1】:

context.openFileOutput(key 将文件写入内存。您可以使用 getFilesDir() 找到的路径类似于 /data/data/<yourpackagename>/files

所以如果你想删除文件'key',你必须将File file = new File(path)的路径设置为String path = getFilesDir().getAbsolutePath() + "/" + key;

并使用 file.exists() 来检查文件是否存在!

【讨论】:

  • 可以这样定义;文件 file = new File(getFilesDir(), fileName);
【解决方案2】:

使用它来清除应用程序数据。

  public void clearApplicationData() 
    {
        File cache = getCacheDir();
        File appDir = new File(cache.getParent());
        if (appDir.exists()) {
            String[] children = appDir.list();
            for (String s : children) {
                if (!s.equals("lib")) {
                    deleteDir(new File(appDir, s));Log.i("TAG", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
                }
            }
        }
    }

    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;
                }
            }
        }
        return dir.delete();
    }

【讨论】:

    【解决方案3】:

    文件

    与缓存目录一样,您的应用也有一个特定于应用的目录来保存文件。此目录中的文件将一直存在,直到应用程序明确删除它们或应用程序被卸载。您通常使用Context.getFilesDir() 访问此目录。这可以在应用信息屏幕上显示为各种内容,但在您的屏幕截图中,这是“USB 存储数据”。

    注意:如果您想明确放置在外部媒体(通常是 SD 卡)上,您可以使用Context.getExternalFilesDir(String type)

    简单的缓存管理器:

    public class CacheManager {
    
        private static final long MAX_SIZE = 5242880L; // 5MB
    
        private CacheManager() {
    
        }
    
        public static void cacheData(Context context, byte[] data, String name) throws IOException {
    
            File cacheDir = context.getCacheDir();
            long size = getDirSize(cacheDir);
            long newSize = data.length + size;
    
            if (newSize > MAX_SIZE) {
                cleanDir(cacheDir, newSize - MAX_SIZE);
            }
    
            File file = new File(cacheDir, name);
            FileOutputStream os = new FileOutputStream(file);
            try {
                os.write(data);
            }
            finally {
                os.flush();
                os.close();
            }
        }
    
        public static byte[] retrieveData(Context context, String name) throws IOException {
    
            File cacheDir = context.getCacheDir();
            File file = new File(cacheDir, name);
    
            if (!file.exists()) {
                // Data doesn't exist
                return null;
            }
    
            byte[] data = new byte[(int) file.length()];
            FileInputStream is = new FileInputStream(file);
            try {
                is.read(data);
            }
            finally {
                is.close();
            }
    
            return data;
        }
    
        private static void cleanDir(File dir, long bytes) {
    
            long bytesDeleted = 0;
            File[] files = dir.listFiles();
    
            for (File file : files) {
                bytesDeleted += file.length();
                file.delete();
    
                if (bytesDeleted >= bytes) {
                    break;
                }
            }
        }
    
        private static long getDirSize(File dir) {
    
            long size = 0;
            File[] files = dir.listFiles();
    
            for (File file : files) {
                if (file.isFile()) {
                    size += file.length();
                }
            }
    
            return size;
        }
    }
    

    注意:缓存的目的是减少网络活动, 长流程,并在您的应用中提供响应式 UI。

    参考:When to clear the cache dir in Android?

    【讨论】:

      猜你喜欢
      • 2013-07-11
      • 1970-01-01
      • 2012-01-04
      • 2020-09-10
      • 2020-11-26
      • 2023-03-31
      • 2017-05-24
      • 2014-08-18
      • 2012-10-22
      相关资源
      最近更新 更多