嗨我需要讀取字節數組作爲對象。然而每當我嘗試打印出Stream CorruptedException。當讀取對象時發生StreamCorrupedException
下面是我寫的代碼
public class TestSave {
public static void main(String[] args) {
String key = "redismap";
Map<String, Object> map = new HashMap<String, Object>();
List<String> list = new ArrayList<String>();
map.put("String", "test");
map.put("List", list);
ObjectOutputStream oos = null;
ByteArrayOutputStream bos = null;
JedisHelper helper = JedisHelper.getInstacne();
Jedis connection = helper.getConnection();
try{
bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(map);
byte[] value = bos.toByteArray();
oos.close();
connection.set(key.getBytes(), value);
}catch(Exception e){e.printStackTrace();}
helper.returnResource(connection);
helper.destroyPool();
System.out.println("DONE!");
}
}
那麼,這是讀碼
public class TestWithdaw {
public static void main(String[] args) {
JedisHelper helper = JedisHelper.getInstacne();
Jedis connection = helper.getConnection();
String key = "redismap";
String result = connection.get(key);
byte[] primalData = result.getBytes();
System.out.println("Byte Arrays : " + Arrays.toString(primalData));
ByteArrayInputStream bis = null;
ObjectInputStream ois = null;
try{
bis = new ByteArrayInputStream(primalData);
ois = new ObjectInputStream(bis);
Object resultMap = ois.readObject();
System.out.println("resultMap : " + resultMap);
ois.close();
}catch(Exception e){e.printStackTrace();}
helper.returnResource(connection);
helper.destroyPool();
}
}
然後,這是我得到的錯誤消息。
java.io.StreamCorruptedException: invalid stream header: EFBFBDEF
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:804)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)
at org.owls.redis.test.TestWithdaw.main(TestWithdaw.java:28)
我不明白這個流頭有什麼問題。 這些都是我已經試過: - <
- 改變列表以矢量編寫代碼。 (串行問題)
感謝您幫助我:d
如果在'bos.toByteArray'之前調用'oos.close',會發生什麼? – immibis
'ObjectOutputStream'被緩衝!您需要在檢索數據前調用'flush()'(或'close()')__。 –
@immibis同樣的結果。它仍然顯示StreamCorruptedException。 –