使用getCacheDir()缓存文件

Hou*_*fly 10 android caching dropbox

我想下载从Dropbox下载的图像并将其缓存以供进一步使用:

String cachePath = mContext.getCacheDir().getAbsolutePath() + entry.fileName();
File cacheFile = new File(cachePath);
//cacheFile.exists() returns true after 1st call
if(!cacheFile.exists()){
  //If cache doesn't exist, download the file
  mFos = new FileOutputStream(cachePath);
  mApi.getThumbnail(path, mFos, ThumbSize.BESTFIT_320x240,
                              ThumbFormat.JPEG, null);
}
mDrawable = Drawable.createFromPath(cachePath);
mImageView.setImageDrawable(mDrawable);
Run Code Online (Sandbox Code Playgroud)

mDrawablenull如果代码不进入if块.

如果我评论if条件它工作正常.但每次下载图像.

编辑:

以上代码来自如何测试缓存中的文件

Bir*_*dia 7

试试这个希望可以帮到你

String path = context.getFilesDir().getAbsolutePath() + File.separator + entry.fileName();
        File file = new File(path);

        if (file.exists()) {
            // File exists
        } else {
            // File does not exist
        }
Run Code Online (Sandbox Code Playgroud)