Java 如何将Hasmap写入文件

Java 如何将Hasmap写入文件,java,android,bitmap,hashmap,Java,Android,Bitmap,Hashmap,尝试将Hasmap字符串、位图写入文件,然后在将来将其返回到Hasmap Error : java.io.NotSerializableException: android.graphics.Bitmap 位图不是一个可序列化的类,所以我怎样才能将它保存到一个文件中并将其取回 //output file fos = new FileOutputStream(Environment.getExternalStorageDirectory() + File.separ

尝试将Hasmap字符串、位图写入文件,然后在将来将其返回到Hasmap

Error : java.io.NotSerializableException: android.graphics.Bitmap
位图不是一个可序列化的类,所以我怎样才能将它保存到一个文件中并将其取回

        //output file 
      fos = new FileOutputStream(Environment.getExternalStorageDirectory() + File.separator +"blts/"+"list.ser");
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(hashmap);
      oos.close();

        //gethashmap
      FileInputStream fis = new FileInputStream(Environment.getExternalStorageDirectory() + File.separator +"blts/"+ "list.ser");
      ObjectInputStream ois = new ObjectInputStream(fis);
      HashList = (HashMap<String, Bitmap>)ois.readObject();
      ois.close();
用于序列化

ByteArrayOutputStream stream = new ByteArrayOutputStream();
currentImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
BitmapDataObject bitmapDataObject = new BitmapDataObject();
bitmapDataObject.serializedBitmap = stream.toByteArray();
bitmapDataObject.serializedBitmap  = "";//your string value
out.writeObject(bitmapDataObject);
用于反序列化

BitmapDataObject bitmapDataObject = (BitmapDataObject) in.readObject();
Bitmap image = BitmapFactory.decodeByteArray(
            bitmapDataObject.imageByteArray, 0,
            bitmapDataObject.imageByteArray.length);
Sting value = bitmapDataObject.getValue();
现在,您应该创建自定义类,而不是使用HashMap

public class BitmapDataObject implements Serializable {

/**
 * 
 */
private static final long serialVersionUID = 1L;
String value;
byte[] serializedBitmap;

public String getValue() {
    return value;
}

public void setValue(String value) {
    this.value = value;
}

public byte[] getSerializedBitmap() {
    return serializedBitmap;
}

public void setSerializedBitmap(byte[] serializedBitmap) {
    this.serializedBitmap = serializedBitmap;
}

}

因为HashMap已经可以序列化,所以不需要替换它。只做一个实现可序列化位图的私有类要方便得多

private static class SerializableBitmap implements Serializable {
    private static final long serialVersionUID = 0L;

    private byte[] _compressedBitmap;

    // constructor compresses bitmap into Serializable form
    public SerializableBitmap(Bitmap bitmap) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        _compressedBitmap = stream.toByteArray();
    }

    // reconstructs Bitmap for actual use
    public Bitmap getBitmap() {
        Bitmap bitmap = BitmapFactory.decodeByteArray(_compressedBitmap, 0,
                _compressedBitmap.length);

        return bitmap;
    }
}

然后,您可以使用HashMap而不是HashMap。

对于带有字符串和位图的HashMap,我如何才能做到这一点?请理解。我想你可以用另一种方式,比如,