将byte数组转为Object

若是使用下面方法,将会报java.io.StreamCorruptedException: invalid stream header: 31323334异常java

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数组进行序列化,web

若是使用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;
}