Android:如何将图像保存到缓存目录?

时间:2012-07-22 14:18:15

标签: android

我看到了很多类似的问题,但是没有人帮助我。我有这样的代码:

String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        //create name based on time? just a simple link to photo
        //save to cache file
        File file = getExternalCacheDir();
        if (file != null) {
            try {
                String root = file.getAbsolutePath();
                File imageFile = new File(file, "m_images.jpeg");
                boolean tr = imageFile.mkdirs();
                FileOutputStream stream = new FileOutputStream(imageFile);
                boolean complete = image.compress(Bitmap.CompressFormat.PNG, 90, stream);
                if (!complete) {
                    Log.d("tag", "image doesn't saved");
                }
                Log.d("tag", "image saved");
            } catch (IOException e) {
                Log.d("tag", "Can't save image", e);
            }

但是当我打开FileOoutputStream时,我总是得到这个异常:

java.io.FileNotFoundException: /mnt/sdcard/Android/data/com.whatever/cache/m_images.jpeg (Is a directory)

你能说出这个问题的原因在哪里?为什么文件没有创建?

1 个答案:

答案 0 :(得分:2)

异常/mnt/sdcard/Android/data/com.whatever/cache/m_images.jpeg (Is a directory) 表示它是一个目录。删除行boolean tr = imageFile.mkdirs();

会很好地执行