将byte数组转为Object
Posted 麦田
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将byte数组转为Object相关的知识,希望对你有一定的参考价值。
如果使用下面方法,将会报java.io.StreamCorruptedException: invalid stream header: 31323334
异常
public static Object toObject(byte[] bytes)
Object obj = null;
try
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bis);
obj = ois.readObject();
ois.close();
bis.close();
catch (IOException ex)
ex.printStackTrace();
catch (ClassNotFoundException ex)
ex.printStackTrace();
return obj;
public static void main(String[] args)
String str = "123456";
byte b[] = str.getBytes();
Object obj = toObject(b);
ObjectInputStream 是进行反序列化,因为反序列化byte数组之前没有对byte数组进行序列化,
如果使用readObject()读取,则必须使用writeObject()
如果使用readUTF()读取,则必须使用writeUTF()
如果使用readXXX()读取,对于大多数XXX值,都必须使用writeXXX()
可使用下面的两种正确方法进行将byte数组转为Object
public static Object toObject(byte[] bytes)
Object obj = null;
try
FileOutputStream fos = new FileOutputStream("d:\\\\a.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(bytes);
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
"d:\\\\a.txt"));
return ois.readObject();
catch (IOException ex)
ex.printStackTrace();
catch (ClassNotFoundException e)
e.printStackTrace();
return obj;
public static Object toObject2(byte[] bytes)
Object obj = new Object();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos;
try
oos = new ObjectOutputStream(baos);
oos.writeObject(bytes);
byte[] strData = baos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(strData);
ObjectInputStream ois = new ObjectInputStream(bais);
obj = ois.readObject();
catch (IOException e)
e.printStackTrace();
catch (ClassNotFoundException e)
e.printStackTrace();
return obj;
以上是关于将byte数组转为Object的主要内容,如果未能解决你的问题,请参考以下文章
javascript怎样将object类型转换成array数组