解决序列化中的问题java.io.StreamCorruptedException: invalid stream header:EFBFBDEF

Java代码  收藏代码
  1. public class TestDeserialize extends TestCase {  
  2.     public void testDeserialize() throws IOException, ClassNotFoundException {  
  3.         ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  4.         ObjectOutputStream oos = new ObjectOutputStream(baos);  
  5.         BigInteger bi = new BigInteger("0");  
  6.         oos.writeObject(bi);  
  7.         String str = baos.toString();  
  8.         System.out.println(str);  
  9.         ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new ByteArrayInputStream(str.getBytes())));  
  10.         Object obj = ois.readObject();  
  11.     }  
  12. }  

 

抛出错误

 

 

Java代码  收藏代码
  1. [junit] ------------- ---------------- ---------------  
  2.    [junit] Testcase: testDeserialize(org.jboss.remoting.loading.TestDeserialize):   Caused an ERROR  
  3.    [junit] invalid stream header: EFBFBDEF  
  4.    [junit] java.io.StreamCorruptedException: invalid stream header: EFBFBDEF  
  5.    [junit]  at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:783)  
  6.    [junit]  at java.io.ObjectInputStream.<init>(ObjectInputStream.java:280)  
  7.    [junit]  at org.jboss.remoting.loading.TestDeserialize.testDeserialize(TestDeserialize.java:20)  
  8.    [junit]   
  9.    [junit]   
  10.    [junit] Test org.jboss.remoting.loading.TestDeserialize FAILED  

 

修改成为

 

 

Java代码  收藏代码
  1. public void testDeserialize() throws IOException, ClassNotFoundException {  
  2.     ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  3.     ObjectOutputStream oos = new ObjectOutputStream(baos);  
  4.     BigInteger bi = new BigInteger("0");  
  5.     oos.writeObject(bi);  
  6.     byte[] str = baos.toByteArray();  
  7.     ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new ByteArrayInputStream(str)));  
  8.     Object obj = ois.readObject();  
  9.     assertNotNull(obj);  
  10.     assertEquals(obj.getClass().getName(),"java.math.BigInteger");  
  11.     assertEquals(((BigInteger)obj).intValue(), 0);  
  12. }  

 

搞定,原因请见

 

http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4968673

 

 

The provided test code serializes an object to a ByteArrayOutputStream,
converts the generated byte array into a string using the
ByteArrayOutputStream.toString() method, converts the string back into a byte
array using the String.getBytes() method, and then attempts to deserialize the
object from the byte array using a ByteArrayInputStream.  This procedure will
in most cases fail because of the transformations that take place within
ByteArrayOutputStream.toString() and String.getBytes(): in order to convert the
contained sequence of bytes into a string, ByteArrayOutputStream.toString()
decodes the bytes according to the default charset in effect; similarly, in
order to convert the string back into a sequence of bytes, String.getBytes()
encodes the characters according to the default charset.

Converting bytes into characters and back again according to a given charset is
generally not an identity-preserving operation.  As the javadoc for the
String(byte[], int, int) constructor (which is called by
ByteArrayOutputStream.toString()) states, "the behavior ... when the given
bytes are not valid in the default charset is unspecified".  In the test case
provided, the first two bytes of the serialization stream, 0xac and 0xed (see
java.io.ObjectStreamConstants.STREAM_MAGIC), both get mapped to the character
'?' since they are not valid in the default charset (ISO646-US in the JDK I'm
running).  The two '?' characters are then mapped back to the byte sequence
0x3f 0x3f in the reconstructed data stream, which do not constitute a valid
header. 

The solution, from the perspective of the test case, is to use
ByteArrayOutputStream.toByteArray() instead of toString(), which will yield the
raw byte sequence; this can then be fed directly to the
ByteArrayInputStream(byte[]) constructor.

注:在转换成字符串的时候如果使用Base64则可以避免该问题
阅读更多
换一批

java.io.StreamCorruptedException: invalid stream header: 41434544

04-17

java.io.StreamCorruptedException: invalid stream header: 41434544rn at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:783)rn at java.io.ObjectInputStream.(ObjectInputStream.java:280)rn at org.hibernate.util.SerializationHelper$CustomObjectInputStream.(SerializationHelper.java:252)rn at org.hibernate.util.SerializationHelper.deserialize(SerializationHelper.java:209)rn at org.hibernate.util.SerializationHelper.deserialize(SerializationHelper.java:240)rn at org.hibernate.type.SerializableType.fromBytes(SerializableType.java:82)rn at org.hibernate.type.SerializableType.get(SerializableType.java:39)rn at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:163)rn at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:154)rn at org.hibernate.type.AbstractType.hydrate(AbstractType.java:81)rn at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:2091)rn at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1380)rn at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1308)rn at org.hibernate.loader.Loader.getRow(Loader.java:1206)rn at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:580)rn at org.hibernate.loader.Loader.doQuery(Loader.java:701)rn at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:236)rn at org.hibernate.loader.Loader.loadEntity(Loader.java:1864)rn at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:48)rn at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:42)rn at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:3039)rn at org.hibernate.event.def.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:399)rn at org.hibernate.event.def.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:375)rn at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:139)rn at org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:195)rn at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:103)rn at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:879)rn at org.hibernate.impl.SessionImpl.get(SessionImpl.java:816)rn at org.hibernate.impl.SessionImpl.get(SessionImpl.java:809)rn at dao.ProjectDao.getProject(ProjectDao.java:20)rn at action.QueryAction.execute(QueryAction.java:32)rn at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431)rn at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236)rn at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)rn at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:432)rn at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)rn at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)rn at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)rn at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)rn at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)rn at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)rn at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)rn at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)rn at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)rn at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:261)rn at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)rn at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:581)rn at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)rn at java.lang.Thread.run(Thread.java:619)

求助: java.io.StreamCorruptedException: invalid stream header: 32303134

12-08

最近,在做一个j2ee的开发,遇到了一个问题,耽误了我一天的时间,不知道该怎么解决,求助大家!rnrn情况如下:rn开发IDE:Intelij IDEArn框架 :使用SSH框架开发。 spring 最新版 4.1.2 ,struts 2.3,Hibernate 4.3.7rnrn问题点:[code=java]rn Transaction tx = sess.beginTransaction();rn String sql = "from NewsType ";rn Query q = sess.createQuery(sql);rn tx.commit();rn result = q.list();[/code] rn问题就在最后一句,我debug时,发现q中的size==0,而且只要q.list()就出问题rnrn具体错误: Caused by: java.io.StreamCorruptedException: invalid stream header: 32303134rnrn整体Exception如下:rn[code=java]rnorg.hibernate.type.SerializationException: could not deserializern at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:262)rn at org.hibernate.internal.util.SerializationHelper.deserialize(SerializationHelper.java:306)rn at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.fromBytes(SerializableTypeDescriptor.java:155)rn at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:130)rn .......rn at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)rn at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)rn at java.lang.Thread.run(Thread.java:745)rn Caused by: java.io.StreamCorruptedException: invalid stream header: 32303134rn [code=java]at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:804)rn at java.io.ObjectInputStream.(ObjectInputStream.java:299)rn at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.(SerializationHelper.java:328)rn at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.(SerializationHelper.java:318)rn at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:237)rn ... 103 morern[/code]

纠结JAVA SOCKET 异常:java.io.StreamCorruptedException: invalid stream header

03-21

异常信息:(客户端发出信息,第一次服务端接收正常,再发服务端就抛出这个异常了,我换成Data类型就可以了,但是我要传的是对象,所以要用Object类型。烦请高手看下。)rnjava.io.StreamCorruptedException: invalid stream header: 74000161rn at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:783)rn at java.io.ObjectInputStream.(ObjectInputStream.java:280)rn at com.nothing.Lab.S$Clients.run(S.java:55)rn at java.lang.Thread.run(Thread.java:619)rnrn服务端:(第二次接收时抛异常)rn[code=Java]rnpackage com.nothing.Lab;rnrnimport java.io.DataInputStream;rnimport java.io.IOException;rnimport java.io.ObjectInputStream;rnimport java.io.ObjectOutputStream;rnimport java.net.ServerSocket;rnimport java.net.Socket;rnrnpublic class S rn rn public ServerSocket serverSocket = null;rn public ObjectInputStream ois = null;rn public ObjectOutputStream oos = null;rn public boolean started = false, bConnect = false;rn rn public static void main(String[] args)rn new S().go();rn rn rn public void go()rn try rn serverSocket = new ServerSocket(8888);rn started = true;rn catch (IOException e) rn // TODO Auto-generated catch blockrn e.printStackTrace();rn rn tryrn while(started)rn Socket s = serverSocket.accept();rn System.out.println("a clients in");rn Clients c = new Clients(s);rn bConnect = true;rn new Thread(c).start();rn rn catch(IOException e)rn e.printStackTrace();rn rn rn rn public class Clients implements Runnablernrn Socket s;rn String str = "";rn public Clients(Socket s)rn this.s = s;rn rn @Overridern public void run() rn // TODO Auto-generated method stubrn tryrn while(bConnect)rn ois = new ObjectInputStream(s.getInputStream()); //第二次接收时抛异常rn str = ois.readObject().toString();rn System.out.println(str);rn rn catch(ClassNotFoundException e1)rn e1.printStackTrace();rn catch(IOException e)rn System.out.println("quit");rn e.printStackTrace();rn finallyrn rn try rn if(ois != null)rn ois.close();rn if(s != null)rn s.close();rn catch (IOException e) rn // TODO Auto-generated catch blockrn e.printStackTrace();rn rn rn rn rn rnrn[/code]rnrn客户端:rn[code=C/C++]rnpackage com.nothing.Lab;rnrnimport java.awt.BorderLayout;rnrnpublic class C extends JFrame rnrn public Socket socket = null;rn public ObjectInputStream ois = null;rn public ObjectOutputStream oos = null;rn private JPanel contentPane;rn private JTextField textField;rnrn /**rn * Launch the application.rn */rn public static void main(String[] args) rn EventQueue.invokeLater(new Runnable() rn public void run() rn try rn C frame = new C();rn frame.go();rn frame.setVisible(true);rn catch (Exception e) rn e.printStackTrace();rn rn rn );rn rnrn /**rn * Create the frame.rn */rn public C() rn setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);rn setBounds(100, 100, 308, 300);rn contentPane = new JPanel();rn contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));rn contentPane.setLayout(new BorderLayout(0, 0));rn setContentPane(contentPane);rn rn textField = new JTextField();rn contentPane.add(textField, BorderLayout.SOUTH);rn textField.setColumns(10);rn rn JTextArea textArea = new JTextArea();rn contentPane.add(textArea, BorderLayout.CENTER);rn rn textField.addActionListener(new EnterDown());rn rn rn public void go()rn tryrn socket = new Socket("127.0.0.1", 8888);rn oos = new ObjectOutputStream(socket.getOutputStream());rn System.out.println("connection");rn catch(IOException e)rn e.printStackTrace();rn rn rn rn rn public class EnterDown implements ActionListenerrn public void actionPerformed(ActionEvent e)rn try rn rn String str = textField.getText();rn System.out.println("c:"+str);rn oos.writeObject(new String("a"));rn// oos.flush();rn// oos.close();rn catch (IOException e1) rn // TODO Auto-generated catch blockrn e1.printStackTrace();rn rn rn rn rn public class recv implements Runnablernrn @Overridern public void run() rn // TODO Auto-generated method stubrn rn rn rn rnrnrn[/code]

没有更多推荐了,返回首页