java.io.StreamCorruptedException: invalid stream header: ABACED00
阿新 • • 發佈:2019-02-08
序列化和反序列化應該成對使用。我們對一個物件進行序列化之後得到的是這個物件對應的二進位制資料,比如說我對一個字串物件進行序列化之後得到是物件的二進位制表示形式;如果你通過string的getBytes方法,可以得到字串物件的資料的二進位制表示形式。這兩種二進位制形式是不一樣的,一個是物件的二進位制表示,一個是物件的資料的二進位制表示,前者包含了物件的資料之外還會包含一些額外的其他資訊,比如說物件的序列化id等等。
因以上原因,我們就不能單單對一個沒有經過序列化的二進位制資料進行反序列化,
public class SerializeTest { public static void main(String args[]) { SerializeTest jt = new SerializeTest(); String s = "helloworld!"; byte[] bt = null; bt = s.getBytes(); ArrayList<String> list = new ArrayList<String>(); list=jt.getArrayList(bt);//這一行會出錯。 } public ArrayList<String> getArrayList(byte[] bt) { ArrayList<String> list = new ArrayList<String>(); ObjectInputStream objIps; //注意這裡,ObjectInputStream 對以前使用 ObjectOutputStream 寫入的基本資料和物件進行反序列化。問題就在這裡,你是直接將byte[]陣列傳遞過來,而這個byte陣列不是使用ObjectOutputStream類寫入的。所以問題解決的辦法就是:用輸出流得到byte[]陣列。 try { objIps = new ObjectInputStream(new ByteArrayInputStream(bt)); list = (ArrayList<String>)objIps.readObject(); } catch (Exception e) { e.printStackTrace(); } return list; }
上面中就是對一個字串物件的資料的byte位元組資料進行反序列化,所以會報出標題錯誤。