从SD卡读取位图时StreamCorruptedException

时间:2011-06-24 18:33:30

标签: android sd-card

我有一个返回jpg的Web服务。我将这个jpg读入一个byte [],转换为Bitmap,并将其保存到SD卡。下次用户访问此活动时,它将在访问Web服务之前搜索SD卡以查看该图像是否存在。

但是,如果文件存在,检查SD卡的代码将返回StreamCorruptedException。

这是我写入SD卡的代码:

if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
    String root = Environment.getExternalStorageDirectory().toString();
    new File(root + "/images").mkdirs();
    try {
        File file = new File(root + "/images", Integer.toString(intImageId) + "m.jpg");
        FileOutputStream os = new FileOutputStream(file);
        Bitmap theImageFromByteArray = BitmapFactory.decodeByteArray(image, 0, image.length);
        theImageFromByteArray.compress(Bitmap.CompressFormat.JPEG, 80, os);
        os.flush();
        os.close();
    }
    catch (FileNotFoundException e) {
    }
    catch (IOException e) {
    }
}

以下是检查SD卡现有图像的代码:

if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
        || Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
    try {
        File file = new File(Environment.getExternalStorageDirectory() + "/images", Integer.toString(mImageId) + "m.jpg");
        FileInputStream fis = new FileInputStream(file);
        ObjectInputStream ois = new ObjectInputStream(fis);
        mImage = (Bitmap)ois.readObject();
        ois.close();
    }
    catch (Exception e) {
    }
}

异常发生在新的ObjectInputStream(fis)

期间

2 个答案:

答案 0 :(得分:0)

考虑到ObjectInputStream构造函数中发生异常,我怀疑您编写的文件有问题。看看this。编写和阅读图像的方法略有不同。

答案 1 :(得分:0)

你不能像这样任意readObject()。需要使用writeObject()以便readObject()检测有效的序列化对象。

相关问题