【问题标题】:How to get files in cache directory in android?如何在android的缓存目录中获取文件?
【发布时间】:2013-11-27 07:00:40
【问题描述】:

在我的 android 应用程序中,我在使用此功能获得的目录中创建文件(注意它放在子目录中)。

gsFile = new File(getCacheDir(), "test/aa.txt");

但是我现在如何遍历该目录中的文件呢?

我试过了

File dir = new File(getCacheDir(), "test/aa.txt");
for (File f : dir.listFiles()) {

}

但它在文件 f 上崩溃了

【问题讨论】:

  • dir 是一个文件它不是一个目录..它没有给你任何列表文件..你不能迭代它..
  • 如何获取目录?

标签: android file


【解决方案1】:

像这样更改您的代码并尝试..

    File dir = new File(getCacheDir(), "test");
    if (dir.exists()) {
        for (File f : dir.listFiles()) {
            //perform here your operation
        }
    }

【讨论】:

  • 什么是 getCacheDir() ?
  • 只是你项目的缓存文件夹
【解决方案2】:

使用下面的代码,您可以获得应用缓存目录中的所有文件,您可以对其进行迭代并执行所需的任何操作

File dir = new File(mContext.getCacheDir().getAbsolutePath());
        if (dir.exists()) {
            for (File f : dir.listFiles()) {
                f.getName();
            }
        }

【讨论】:

  • mContext.getCacheDir() 本身返回绝对路径,不需要在链式调用中使用getAbsolutePath()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-19
  • 1970-01-01
  • 2012-09-10
  • 2019-11-08
  • 1970-01-01
  • 1970-01-01
  • 2015-06-27
相关资源
最近更新 更多