سؤال

i try to serialize Map. this is my function:

Map<Integer,Word> currentMap=new LinkedHashMap<Integer,Word>();

protected void serializeCM(){
    try{
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream os = new ObjectOutputStream(bos);
        os.writeObject(currentMap);
        String SO = bos.toString();
        os.flush();
        os.close();
        writeFile("serialized.txt",SO,false);
    }
    catch(Exception e){e.printStackTrace();}
}

after i try to deserialize currentMap

protected Map<Integer,Word> deserializeCM(String f){
    Map<Integer,Word> map=new LinkedHashMap<Integer,Word>();
    String path=System.getProperty("user.dir")+"\\";
    try{
        String str=new String(Files.readAllBytes(Paths.get(path+f)));
        ByteArrayInputStream bis = new ByteArrayInputStream(str.getBytes());
        ObjectInputStream is = new ObjectInputStream(bis);
        map = (LinkedHashMap<Integer,Word>)is.readObject();         
        is.close();
        return map;
    }
    catch(Exception e){e.printStackTrace();};
    return null;
}

this is how word class looks:

public class Word implements Cloneable, Serializable{

public String l;
public String cap="";
public byte rPos;
public byte time;
public byte a_index;
public byte master = -1;
public Map<Integer,Word> enumerations = new HashMap<Integer,Word>();
public Map<Integer,Boolean> contrs = new HashMap<Integer,Boolean>();

public Object clone(){
    try{return super.clone();}
    catch(Exception e){e.printStackTrace();return this;}
}

}

and when i try to deserialize it it gets me this error

java.io.StreamCorruptedException: invalid stream header: EFBFBDEF

what am i doing wrong?

any help appriciated!

هل كانت مفيدة؟

المحلول

Write directly to file without using ByteArrayInputStream / ByteArrayOutputStream.

Serialization:

protected void serializeCM() {
    try {
        ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("serialized.txt"));
        os.writeObject(currentMap);
        os.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Deserialization:

protected Map<Integer, Word> deserializeCM(String f) {
    String path = System.getProperty("user.dir") + "\\" + f;

    try {
        Map<Integer, String> map = new LinkedHashMap<Integer, Word>();
        ObjectInputStream is = new ObjectInputStream(new FileInputStream(path));
        map = (LinkedHashMap<Integer, Word>) is.readObject();
        is.close();

        return map;
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top