将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;
}
©️2020 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客 返回首页