2014-04-29 157 views
0

我嘗試序列化Map。這是我的函數:如何反序列化映射對象

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();} 
} 

後,我嘗試反序列化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; 
} 

這是詞類的樣子:

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;} 
} 

}

,當我嘗試反序列化它讓我這個錯誤

java.io.StreamCorruptedException: invalid stream header: EFBFBDEF 

我做錯了什麼?

任何幫助appriciated!

+1

重複。字符串不是二進制數據的容器。寫出100次。 – EJP

回答

2

直接寫入文件,而無需使用ByteArrayInputStream的/ByteArrayOutputStream

連載:

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

反序列化:在我之後

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; 
}