Java异常之invalid stream header: 00000000

Java异常之invalid stream header: 00000000

java.io.StreamCorruptedException: invalid stream header: 00000000
	at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:866)
	at java.io.ObjectInputStream.(ObjectInputStream.java:358)
	at Test.B.clone(B.java:25)
	at Test.B.main(B.java:44)
java.lang.NullPointerException
	at Test.B.main(B.java:45)

源码如下:

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class B implements Cloneable, Serializable {
	private static final long serialVersionUID = 1;
	public String name;
	A a =new A();
	

	public B clone() {
		ByteArrayOutputStream baos=new ByteArrayOutputStream();
		
		try {
			byte bytes[]=new byte[50];
			ObjectOutputStream oos=new ObjectOutputStream(baos);
			oos.writeObject(this);
			ByteArrayInputStream bais=new ByteArrayInputStream(bytes);
			ObjectInputStream ois=new ObjectInputStream(bais);
			Object obj=null;
			while((obj=ois.readObject())!=null)
			{
				return (B) obj;
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
		return null;
	}
	public static void main(String[] args) {
		B b=new B();
		try {
			B clone = b.clone();
			clone.a.id=10;
			System.out.println(clone.a.id);
			System.out.println(b.a.id);
			
		} catch (Exception e) {
			
			e.printStackTrace();
		}
	}

}

简单来说是传入了空的数组对象导致的异常,将传入的byte数组改为baos.toByteArray())就可以解决了

package Test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class B implements Cloneable, Serializable {
	private static final long serialVersionUID = 1;
	public String name;
	A a =new A();
	

	public B clone() {
		ByteArrayOutputStream baos=new ByteArrayOutputStream();
		
		try {
//			byte bytes[]=new byte[50];
			ObjectOutputStream oos=new ObjectOutputStream(baos);
			oos.writeObject(this);
			ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());
			ObjectInputStream ois=new ObjectInputStream(bais);
			Object obj=null;
			while((obj=ois.readObject())!=null)
			{
				return (B) obj;
			}
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
		return null;
	}
	public static void main(String[] args) {
		B b=new B();
		try {
			B clone = b.clone();
			clone.a.id=10;
			System.out.println(clone.a.id);
			System.out.println(b.a.id);
			
		} catch (Exception e) {
			
			e.printStackTrace();
		}
	}

}

完美解决

你可能感兴趣的:(Java)