StreamCorruptedException problem

I am trying to append serialized objects to a file without doing it all at once, ie, writing some objects to the file (for example three objects), ending the application, closing the object input stream and file storing the serialized objects. Late I would restarting the application and add more objects (say two objects), so the file grows over time.
I have a simple objectWriter class. In the add object program I create an instance of objectWriter, write some instances of the serialized class to the input stream, then close it. It looks like this:
ow = new ObjectWriter();
//write one or more serialized 'Contact' objects
ContactObject co = new ContactObject( string1, string2 );
ow.writeObject(co);
//Finish up
ow.closeOOStream();
The ObjectWrite constructor and methods look like this:
public ObjectWriter()
try
FileOutputStream fos = new FileOutputStream("ContactFile.ser", true);
oos = new ObjectOutputStream(fos);
catch (Exception e) {....}
public void writeObject(ContactObject _co)
try
oos.writeObject(_co);
catch (Exception e) {..}
public void closeOOStream()
try
oos.close();
catch (Exception e) {}
The append application seems to work without exception and when I examine the ContactFile.ser file, there does appear to be five objects in there.
But when I employ an ObjectReader class I get the error StreamCorruptedException after the third object is read. I wonder if it is therefore possible
to serialize objects in this way or must one use conventional text-based flat files to achieve such an end.
Thanks for any help.

qabpafi wrote:
Thanks for the interest Paul. Your comments are certainly worth taking into account.If you're interested in this approach, I can post a few details about this.
In order to encapsulate multiple streams into a single stream, you need to write the length of each stream so that the InputStream wrapper can read this to determine when to stop returning bytes, or how many bytes to skip in order to reach the next encapsulated stream. Since streams are generally not seekable (mark/reset is optional and limited in size), a block protocol should be used.
In particular, one way of doing this is to buffer the output as it is being written, and when the buffer is full, write the length of the buffer followed by the contents of the buffer. A block length of 0 can be a sentinel value indicating the end of a stream (and the start of the next stream). This way, an InputStream can pick these up and know when to stop returning bytes to the caller. Or, if not all the bytes are read, a request to move to the next stream can continue reading blocks until the 0-length block is encountered, indicating it's at the next stream.

Similar Messages

  • Reg. StreamCorruptedException

    Hi,
    Can U help me How 2 solve "StreamCorruptedException" problem.
    This exception i'm getting when i'm trying 2 use readObject().
    First time it is giving EOFException().from next time onwards it is giving StreamCorruptedException().
    code is:
    import java.io.*;
    public class FileTry1
    // instance variables - replace the example below with your own
    private UserRec currUser;
    * Constructor for objects of class FileTry1
    public FileTry1()
    // initialise instance variables
    UserRec u1 = new UserRec(0, "John3", 1000);
    UserRec u2 = new UserRec(1, "joe3", 2000);
    UserRec u3 = new UserRec(100, "naren", 2000);
    try {
    FileOutputStream ostream = new FileOutputStream("t.tmp", true);
    ObjectOutputStream p = new ObjectOutputStream(ostream);
    p.writeObject(u1);
    p.writeObject(u2);
    p.writeObject(u3);
    p.flush();
    ostream.close();
    p.close();
    catch (Exception e) {
    System.out.println(e);
    } // end catch
    ReadIt ri = new ReadIt();
    public static void main(String args[] ) {
    new FileTry1();
    System.exit(0);
    } // end class FileTry1
    import java.io.*;
    public class UserRec implements Serializable
    // instance variables - replace the example below with your own
    public int userID;
    public String userName;
    public int salary;
    * Constructor for objects of class UserRec
    public UserRec()
    // initialise instance variables
    userID = 0;
    userName = "";
    salary = 0;
    public UserRec(int id, String name, int sal) { 
    // overridden constructor w/ values
    userID = id;
    userName = name;
    salary = sal;
    } // end constructor...
    import java.io.*;
    public class ReadIt
    // instance variables - replace the example below with your own
    private UserRec urec;
    * Constructor for objects of class ReadIt
    public ReadIt()
    // initialise instance variables
    urec = new UserRec();
    FileInputStream istream = null;
    ObjectInputStream p = null;
    // now try to read the file we just wrote
    try {
    istream = new FileInputStream("t.tmp");
    p = new ObjectInputStream(istream);
    System.out.println("Now going to try to read the file back in");
    boolean EOF = false;
    int count=0;
    while ( !EOF ) {
    try {
    UserRec t_urec = (UserRec) p.readObject();
    System.out.println("rec No.: " + t_urec.userID + " Name: " + t_urec.userName);
    if(++count == 4) break;
    } // end try
    catch (Exception f) {
    EOF = true;
    System.out.println("in ReadIt at EOF catch: " + f);
    f.printStackTrace();
    } // end catch EOF
    } // end while ( !EOF )
    istream.close();
    p.close();
    } // end try
    catch (Exception ee) {
    System.out.println("Overall ReadIt catch: " +ee);
    } // end ReadIt()
    } // end class ReadIt
    Thanks in advance
    Naren.

    in ReadIt class you make 4 as 3 For your convinenece i am pasting all the files back compiled and runned,
    import java.io.*;
    public class FileTry1
    // instance variables - replace the example below with your own
    private UserRec currUser;
    * Constructor for objects of class FileTry1
    public FileTry1()
    // initialise instance variables
    UserRec u1 = new UserRec(0, "John3", 1000);
    UserRec u2 = new UserRec(1, "joe3", 2000);
    UserRec u3 = new UserRec(100, "naren", 2000);
    try {
    FileOutputStream ostream = new FileOutputStream("t.tmp", true);
    ObjectOutputStream p = new ObjectOutputStream(ostream);
    p.writeObject(u1);
    p.writeObject(u2);
    p.writeObject(u3);
    p.flush();
    p.close();
    ostream.close();
    catch (Exception e) {
    System.out.println(e);
    } // end catch
    ReadIt ri = new ReadIt();
    public static void main(String args[] ) {
    new FileTry1();
    System.exit(0);
    } // end class FileTry1
    import java.io.*;
    public class ReadIt
    // instance variables - replace the example below with your own
    private UserRec urec;
    * Constructor for objects of class ReadIt
    public ReadIt()
    // initialise instance variables
    urec = new UserRec();
    FileInputStream istream = null;
    ObjectInputStream p = null;
    // now try to read the file we just wrote
    try {
    istream = new FileInputStream("t.tmp");
    p = new ObjectInputStream(istream);
    System.out.println("Now going to try to read the file back in");
    boolean EOF = false;
    int count=0;
    while ( !EOF ) {
    try {
    UserRec t_urec = (UserRec) p.readObject();
    System.out.println("rec No.: " + t_urec.userID + " Name: " + t_urec.userName);
    if(++count == 3) break;
    } // end try
    catch (Exception f) {
    EOF = true;
    System.out.println("in ReadIt at EOF catch: " + f);
    f.printStackTrace();
    } // end catch EOF
    } // end while ( !EOF )
    istream.close();
    p.close();
    } // end try
    catch (Exception ee) {
    System.out.println("Overall ReadIt catch: " +ee);
    } // end ReadIt()
    } // end class ReadIt
    import java.io.*;
    public class UserRec implements Serializable
    // instance variables - replace the example below with your own
    public int userID;
    public String userName;
    public int salary;
    * Constructor for objects of class UserRec
    public UserRec()
    // initialise instance variables
    userID = 0;
    userName = "";
    salary = 0;
    public UserRec(int id, String name, int sal) {
    // overridden constructor w/ values
    userID = id;
    userName = name;
    salary = sal;
    } // end constructor...
    }All The Best

  • Problems moving from 1.3.1 to 1.4 (StreamCorruptedException)

    Hi all,
    I'm having a terrible time moving my existing project from 1.3 to 1.4. The GUI (running on W2k) works fine, but the server side of the app (running on Solaris 2.6 w/ current patches & Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0-b92)) is giving me fits in a couple of places. The app has been in production for over a year using 1.3.1.
    Everything has gone smoothly with the exception of a couple of problems that I just can't seem to get around. Namely, I get UnmarshalExceptions with nested StreamCorruptedExceptions on some of the RMI calls. Everything I send across the wire implements Serializable.
    I got around the first one - Sending an array of objects that each had as a member variable a java.text.MessageFormat object blew up with the before mentioned exception. Wierd thing is, if I send just one of those objects it's not a problem, only when sending an array of them is it bad. Changing the type to String and then creating MessageFormat objects from those strings lazily on the client got around the problem. (yuck)
    Anyways, I now have two more issues similar to the above mentioned that I can't seem to find a work-around for. These objects only contain data members of primitive and/or String type. They also implement Serializable, so I can't understand what the problem is. Below is a copy of the exception I'm getting.
    |java.rmi.ServerException: RemoteException occurred in server
    thread; nested exception is:
    java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
    java.io.StreamCorruptedExceptionjava.rmi.ServerException: RemoteException occurred in server thread; nested excepti
    on is:
    java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
    java.io.StreamCorruptedException
    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:292)
    at sun.rmi.transport.Transport$1.run(Transport.java:148)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.Transport.serviceCall(Transport.java:144)
    at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:460)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:701)
    at java.lang.Thread.run(Thread.java:536)
    at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:247)
    at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:223)
    at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:133)
    at com.<myco>.<myprod>.interfaces.<host>.Service_Stub.getResponse(Unknown Source)
    at com.<myco>.<myprod>.interfaces.<host>.Factory.getResponse(Factory.java:182)
    at com.<myco>.<myprod>.maintenance.hosts.MaintenanceHost.getWorkload(MaintenanceHost.java:812)
    at com.<myco>.<myprod>.maintenance.MaintenanceService.getWorkload(MaintenanceService.java:2359)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:324)
    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:261)
    at sun.rmi.transport.Transport$1.run(Transport.java:148)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.Transport.serviceCall(Transport.java:144)
    at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:460)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:701)
    at java.lang.Thread.run(Thread.java:536)
    Caused by: java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
    java.io.StreamCorruptedException
    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:249)
    ... 6 more
    Caused by: java.io.StreamCorruptedException
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1291)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1830)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1756)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1636)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1264)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1830)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1756)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1636)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1264)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:322)
    at sun.rmi.server.UnicastRef.unmarshalValue(UnicastRef.java:297)
    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:246)
    ... 6 more
    I've utilized 1.4's ability to getCause(), get the StackTraceElement[] of it, and iterate to see what is present in the "...6 more". If anyone needs to see that to help me, I'll gladly post it as well.
    Thanks in advance for any assistance, I've spent way too much time working on this issue.
    Eric

    I found this thread while searching for an answer to my question and I am wondering if there is any update. Here is my situation...
    We have a 100% Java application which utilizes RMI only. It has been running in production on the 1.2.2 JDK for over four years in many operating environments (Solaris 8, 9, Windows 9x, 2K and XP, Linux).
    We have finally decided to bite the bullet and upgrade the app to 1.4.2 (specifically the _04 release).
    We are getting the StreamCorruptedException consistently. After narrowing the problem we have uncovered that the issue is, indeed, directly related to java.text.Format decendants (in this case SimpleDateFormat and DecimalFormat.
    We have a class (call it OurClass)which includes a SimpleDateFormat instance. SimpleDateFormat implements Serializable (as does OurClass). When an object of OurClass is enstantiated an instance of SimpleDateFormat is created. When this class is passed as a parameter to a server call and needs to be serialized the StreamCorruptedException is thrown. If we comment out the "new SimpleDateFormat()" the code completes successfully.
    The same is true for DecimalFormat.
    What gives? This thread started in late '02 and was last addressed here in early '03. I see that someone posted that some problems can be expected in RMI over IIOP but we have a Java-to-Java RMI-only application.

  • Problem with StreamCorruptedException: invalid stream header: 3C68746D

    Hi
    I am attempting to code a project in Java which involves the user of object serialization to send a String via serialization from an applet embedded in a JSP tp a servlet all files are running on the same machine for testing purposes.
    However I seem to be getting StreamCorruptedException: invalid stream header: 3C68746D whenever I attempt to read the inputstream once I have written to it.
    My code is as follows below (I apologise for the lack of details I have attempted to comment and simplify my code as much as possible for improved readability)
    ////////////////////////APPLET CODE////////////////
    import java.io.*;
    import java.io.Serializable;
    import javax.servlet.http.*;
    import java.applet.*;
    import javax.swing.*;
    import java.net.*;
    *Compiled using netbeans 5.1
    *Uses Apache server embedded with netbeans
    *JSP address http://localhost:8084/TestServ
    *Applet is embedded within this page
    *Servlet address http://localhost:8084/TestServ/TServ
    public class Main extends javax.swing.JApplet {
    JFrame jf;//frame for the test applet
    JTextArea jt;//result text box
    public Main() {
    jt=new JTextArea();//set up applet
    this.add(jt);
    URL servletURL;
    HttpURLConnection servletConnection;
    InputStream iStream=null;
    try
    {   //this address as far as is known is correct
    servletURL = new URL( "http://localhost:8084/TestServ/TServ" );
    //open connection to servlet
    servletConnection = (HttpURLConnection)servletURL.openConnection();
    //set up connection
    servletConnection.setDoInput(true);
    servletConnection.setDoOutput(true);
    servletConnection.setUseCaches(false);
    servletConnection.setDefaultUseCaches(false);
    //have tried "GET" and "POST" and "PUT"(PUT not directly compatible with apache servers)
    servletConnection.setRequestMethod("POST");
    servletConnection.setRequestProperty("Content-type","application/octet-stream");
    /*Have also tried application/x-java-serialized-object*/
    //set object output stream
    ObjectOutputStream outStream =
    new ObjectOutputStream(servletConnection.getOutputStream());
    //write a string for test purposes (As far as I am aware String implements Serializable)
    outStream.writeObject("h");
    //flush and close connection
    //have tried a combination of flush and/or close
    outStream.flush();
    outStream.close();
    //get input stream rdy for objectinput stream
    iStream = servletConnection.getInputStream();
    catch(IOException e)
    jt.setText("Error in output "+e);
    ObjectInputStream oInStream=null;
    String str = iStream.toString();
    //iStream at this point equals ""sun.net.www.protocol.http.HttpURLConnection$HttpInputStream@6754d6
    try
    //this is where the error occurs
    //upon even trying to create a objectinputstream using iStream IOException occurs
    oInStream = new ObjectInputStream(iStream);
    //program does not get any further
    oInStream.close();
    catch(IOException e)
    //this error has been driving me crazy :(
    jt.setText("Error in input "+e);
    Servlet code is below however it does not even reach this point
    (If reading input stream is removed from the applet the servlet provides the same error message)
    /////////////////////Servlet code (however does not reach this point)///////////////
    import java.io.*;
    import java.net.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class TServ extends HttpServlet {
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    ObjectInputStream inputFromApplet = null;
    InputStream in = request.getInputStream();
    BufferedReader inTest = null;
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Servlet TServ</title>");
    out.println("</head>");
    out.println("<body>");
    try
    inputFromApplet = new ObjectInputStream(in);
    out.println("<h2>Sucess </h1>");
    catch(EOFException e)
    out.println("<h3>ERROR: " e " Error</h3>");
    out.println("<h3>End Servlet</h3>");
    out.println("</body>");
    out.println("</html>");
    out.close();
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    processRequest(request, response);
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    processRequest(request, response);
    public String getServletInfo() {
    return "Short description";
    Thank you for your time I have searched for an answer for some time now and how found people in similar situations however no solution has been found
    Any help is appreciated
    Az

    The servlet isn't writing any objects back in reply. It is writing text. Not the same thing. If you want to read using an ObjectInputStream you have to write using an ObjectOutputStream.

  • StreamCorruptedException: does not contain a serialized object?

    Can someone tell me why am I getting this exception:
    C:\javapr>java FetchObject
    Couldn't retrieve binary data: java.io.StreamCorruptedException: InputStream
    does not contain a serialized object
    java.io.StreamCorruptedException: InputStream does
    not contain a serialized object
    at java.io.ObjectInputStream.readStreamHeader
    (ObjectInputStream.java:849)
    at java.io.ObjectInputStream.<init>
    (ObjectInputStream.java:168)
    at FetchObject.main(FetchObject.java:23)
    import java.sql.*;
    import java.util.*;
    import java.io.*;
    class FetchObject implements Serializable {
        public static void main (String[] args) {
            try {
                String driver = "oracle.jdbc.driver.OracleDriver";
                Class.forName(driver);
                String url = "jdbc:oracle:thin:@mymachine:1521:homedeva";
                Connection conn = DriverManager.getConnection(url,"cnn","cnn");
                FetchObject i = new FetchObject();
                    // Select related
                    try
                         byte[] recdBlob = i.selectBlob( 1 , conn ); 
                         ByteArrayInputStream bytes = new ByteArrayInputStream(recdBlob);
                         ObjectInputStream deserialize = new ObjectInputStream( bytes );
              Employee x = (Employee)deserialize.readObject();
                    catch( Exception ex )
                  System.err.println("Couldn't retrieve binary data: " + ex);
                  ex.printStackTrace();
         catch( Exception ex )
              ex.printStackTrace();
        public byte[] selectBlob( int id, Connection conn )
         byte[] returndata = null;
         try
              Statement stmt = conn.createStatement();
              String sql = "SELECT id, rowdata FROM blobs WHERE id = " + id;
              ResultSet rs = stmt.executeQuery(sql);
              if ( rs.next() )
                           try
                               ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
                               BufferedInputStream bis = new BufferedInputStream( rs.getBinaryStream("rowdata") );
                             byte[] bindata = new byte[4096];
                               int bytesread = 0;
                               if ( !rs.wasNull() )
                                       if ( (bytesread = bis.read(bindata,0,bindata.length)) != -1 )
                                          baos.write(bindata,0,bytesread);
                                returndata = baos.toByteArray();
                             baos.flush();
                                bis.close();
                       catch ( Exception ex )
                            System.err.println("Problem retrieving binary data: " + ex);
                        rs.close();
                         stmt.close();  
               catch ( Exception ex )
                    System.err.println("Couldn't retrieve binary data: " + ex);
            return returndata;
    import java.io.*;
    class Employee implements Serializable
         private String lastName;
         private String firstName;
         public Employee(String lastName, String firstName)
              this.lastName = lastName; 
              this.firstName = firstName;
    }

    To clarify I have stored an Employee Object as a Blob in the Oracle database and am attempting to retreive the
    Employee Object from this Blob.
    Thanks

  • SOAP Message Attachment MIME Problem

    Hi there,
    I'm having problem trying to send a binary file with SOAP.
    I can send an XML Doc (MIME type text/xml) but when I try to put the ByteArrayInputStream that holds the binary file and the content to application/octec-stream
    I got this exception:
    javax.activation.UnsupportedDataTypeException: no object DCH for MIME type application/octet-stream
         at javax.activation.ObjectDataContentHandler.writeTo(DataHandler.java:851)
         at javax.activation.DataHandler.writeTo(DataHandler.java:305)
         at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:1089)
         at javax.mail.internet.MimeBodyPart.writeTo(MimeBodyPart.java:635)
         at javax.mail.internet.MimeMultipart.writeTo(MimeMultipart.java:233)
         at com.sun.xml.messaging.soap.MessageImpl.saveChanges(MessageImpl.java:371)
    Anyone had this problem ?
    Any work around ?
    Or this is a problem because the JAXM is not fineshed yet ?
    Thanks,
    Marcio

    Hey guys... I pray you are all still listening.
    I have been on the most mind numbing cookie trail ever (I'm blatantly lying - I'm a Java programmer!) following these blasted exception trails to an 'Unknown Source'
    After initially reading this thread I quickly knocked up ObjectDataSource as follows:
    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.OutputStream;
    import java.io.Serializable;
    import javax.activation.DataSource;
    public class ObjectDataSource
    implements DataSource
         public static final long serialVersionUID;
         public static final String CONTENT_TYPE;
         static {
              serialVersionUID = 42L;
              CONTENT_TYPE = "application/x-java-serialized-object";
         } // end static initializer
         private byte[] objectBytes;
         private String contentId;
         public ObjectDataSource(Serializable object, String contentId)
         throws IOException
              if (contentId == null || contentId.equals(""))
                   this.contentId = object.getClass().getName();
              else
                   this.contentId = contentId;
              ByteArrayOutputStream baoStream = new ByteArrayOutputStream();
              ObjectOutputStream ooStream = new ObjectOutputStream(baoStream);
              ooStream.writeObject(object);
              ooStream.flush();
              ooStream.close();
              objectBytes = baoStream.toByteArray();
         } // end primary constructor
         public InputStream getInputStream()
         throws java.io.IOException
              ByteArrayInputStream baiStream = new ByteArrayInputStream(objectBytes);
              return new ObjectInputStream(baiStream);
         } // end getInputStream
         public OutputStream getOutputStream()
         throws java.io.IOException
              throw new IOException("Cannot write to this stream");
         } // end getOutputStream
         public String getContentType()
              return CONTENT_TYPE;
         } // end getContentType
         public String getName()
              return contentId;
         } // end getName
    } // end ObjectDataSource classand use it as follows:
    AttachmentPart attachment = soapResponse.createAttachmentPart();
    ObjectDataSource ods = new ObjectDataSource(requestedObject, null);
    attachment.setDataHandler(new DataHandler(ods));
    attachment.setContentId(ods.getName());
    soapResponse.addAttachmentPart(attachment);
    soapResponse.saveChanges();... this is within my 'SOAPServlet extends JAXMServlet' servlet, which happens to work fine when testing the servlet outside a web-container. But testing with Tomcat 5.5.x It doesn't work... infact, it damn well dissappears. I try readObject after retrieving and casting the InputStream to an ObjectInputStream from the AttachmentPart, but I get a:
    Exception in thread "main" java.lang.ClassCastException: java.io.ByteArrayInputStream which is totally bizzare!
    So I do a bit of investigation to discover ....
    application/x-java-serialized-object
    java.lang.String
    javax.mail.internet.MimePartDataSource
    java.io.ByteArrayInputStream
    0 // this would be the available bytes in the ByteArrayInputStreamNow the first two lines confirm my ObjectDataSource is there somewhere or that that data was sent over the wire (ha, i'm on the same damn machine), but where the hell did MimePartDataSource come from?
    I have previously encountered the various exceptions including java.io.EOFException when trying to read from the byte stream and java.io.StreamCorruptedException when wrapping that byte stream with an object stream.
    These setbacks have royally ****ed my project; cahnces are slim that it will get finished. I'm ready to give up.
    Any help will be appreciated?
    Warm regards,
    Darren B

  • ObjectInputStream problems

    Hi
    I'm getting slightly desperate after 3 days stuck with the same problem.
    I'm writing a small client server application that contains a chat room. when I use a printwriter combined with a BufferedReader on the sockets everything works perfectly.
    However, I need to send objects to keep a state for some additinbal functionality, and when I change the printwriter/BufferedReader to a ObjectOutputStream/ObjectInputStream I keep getting a StreamCorruptedException on the client.
    It goes like this. As long as I keep sending objects from the server, the client receives them well, but as soon as the server stop sending (waiting for som GUI interaction) I get the exception. As I understand it, the program is supposed to wait at the in.readUTF(); line and then continue when it receives data, but it doesn't wait. It just throws an exception as soon as it stops receiving data.
    I don't think it has anything to do with the read method. Apparently it is the ObjectInputStream complaing when receiving no data.
    Does anyone have an explanition for this?

    I'm not sure exactly how you're "changing the printwriter/BufferedReader to a ObjectOutputStream/ObjectInputStream", but the problem is probably that you're sending binary data (ObjectOutputStream) into a text stream (PrintWriter). If you need to send both binary and text data, then I think you will have to set up two sets of streams.

  • UTFDataFormatException and StreamCorruptedException

    We have an applet client that is communicating with a servlet in Apache Tomcat through HttpUrlConnection
    using ObjectOutputStream / ObjectInputStream.
    Everything has been working fine, but recently one of our users has had some serious problems
    with the client-server communication. Basically this occurs so that client will throw
    UTFDataFormatExceptions and StreamCorruptedExceptions to Java console. These exceptions are
    thrown pretty randomly, for example sometimes 10 times in a row (out of 10 tries) and then
    a few times with no errors and after that more exceptions and so on.
    These exceptions are thrown when client is loading quite a big chunk of data from server.
    According to server access-logs something between 1500000 and 2000000 bytes are transferred.
    Server side logs show no errors.
    JDK on server is 1.4.2_xx and client side Java plug-in is 1.5.0_xx. We have tried different
    Java plug-in versions with no change.
    Other users get those exceptions too when using this particular environment, but less frequently.
    I've tried to debug the applet and the funny thing is, that when I'm running the applet through
    my IDE (JBuilder) I get no exceptions.

    ejp wrote:
    What you're doing with all the extra buffering is pointless and error-prone. Get rid of the ByteArrayOutputStream and ByteArrayInputStream and connect the ObjectInputStream and ObjectOutputStream directly to the socket.Actually the reason for the extra buffering is due to the use of nio channels. I was basically following the advice from http://forum.java.sun.com/thread.jspa?threadID=449283&messageID=2040791 , i.e.,
    dmbdmb wrote:
    You could always call layer an ObjectOutputStream ontop of a ByteArrayOutputStream, write the objects, then grab the bytes from the ByteArrayOutputStream and write them with niobut unfortunately I still got the above exceptions using the scheme described. Are there other reliable ways to accomplish the same task?

  • Problem with Jasper Reports

    hi evrybody... i'm having a problem while using Jasper Reports. I'm trying to Export a jrxml file generated by JasperAssistant plug-in in eclipse. but all i'm having is an exception. the following is my code and the said exception:
    CODE:
    public class DataSourceApp
    private static final String TASK_HTML = "html";
    private static final String TASK_XLS = "xls";
    private static final String TASK_CSV = "csv";
    private static final String TASK_RUN = "run";
    public static void main(String[] args)
    String fileName = null;
    String taskName = null;
    taskName = "html";
    fileName = "path\\DataSourceReport.jasper";
    try
    long start = System.currentTimeMillis();
    if (TASK_HTML.equals(taskName))
    JasperPrint jPrint = new JasperPrint();
    HashMap parameters = new HashMap();
    Connection con = null;
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    con=DriverManager.getConnection("jdbc:odbc:BOM_DSN","","");
    jPrint = JasperFillManager.fillReport("path\\DataSourceReport.jrxml", parameters, con);
    JasperExportManager.exportReportToHtmlFile(fileName);
    System.err.println("HTML creation time : " + (System.currentTimeMillis() - start));
    System.exit(0);
    catch (JRException e)
    e.printStackTrace();
    System.exit(1);
    catch (Exception e)
    e.printStackTrace();
    System.exit(1);
    EXCEPTION:
    java.io.StreamCorruptedException: invalid stream header
         at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:737)
         at java.io.ObjectInputStream.<init>(ObjectInputStream.java:253)
         at net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:84)
         at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:161)
         at datasource.DataSourceApp.main(DataSourceApp.java:184)
    NESTED BY :
    java.io.StreamCorruptedException: invalid stream header
         at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:737)
         at java.io.ObjectInputStream.<init>(ObjectInputStream.java:253)
         at net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:84)
         at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:161)
         at datasource.DataSourceApp.main(DataSourceApp.java:184)
    NESTED BY :
    net.sf.jasperreports.engine.JRException: Error loading object from file : C:\Eclipse\eclipse\workspace\test\BOM_Package\DataSourceReport.jrxml
         at net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:89)
         at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:161)
         at datasource.DataSourceApp.main(DataSourceApp.java:184)
    Caused by: java.io.StreamCorruptedException: invalid stream header
         at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:737)
         at java.io.ObjectInputStream.<init>(ObjectInputStream.java:253)
         at net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:84)
         ... 2 more
    hope you can help me asap.. thanks!
    --joms                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    HI All
    I am working on Jasper report Project and when i am filling the report through
    JasperFillManager.fillreport(String sourceFileName,Map parameters,Connection conn)
    I am getting following exception:(I have included common-collections 3.2.jar in my classpath)
    java.lang.NoClassDefFoundError: org/apache/commons/collections/ReferenceMap
         at net.sf.jasperreports.engine.design.JRAbstractJavaCompiler.<clinit>(JRAbstractJavaCompiler.java:58)
         at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
         at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
         at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
         at java.lang.reflect.Constructor.newInstance(Constructor.java:494)
         at java.lang.Class.newInstance0(Class.java:350)
         at java.lang.Class.newInstance(Class.java:303)
         at net.sf.jasperreports.engine.JasperCompileManager.getCompiler(JasperCompileManager.java:489)
         at net.sf.jasperreports.engine.JasperCompileManager.loadEvaluator(JasperCompileManager.java:243)
         at net.sf.jasperreports.engine.fill.JRFillDataset.createCalculator(JRFillDataset.java:411)
         at net.sf.jasperreports.engine.fill.JRBaseFiller.<init>(JRBaseFiller.java:418)
         at net.sf.jasperreports.engine.fill.JRVerticalFiller.<init>(JRVerticalFiller.java:77)
         at net.sf.jasperreports.engine.fill.JRVerticalFiller.<init>(JRVerticalFiller.java:59)
         at net.sf.jasperreports.engine.fill.JRFiller.createFiller(JRFiller.java:147)
         at net.sf.jasperreports.engine.fill.JRFiller.fillReport(JRFiller.java:57)
         at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:402)
         at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:234)
    Please Suggest ;Thanks in advance

  • Zip/unzip problem

    I have a problem unzipping Objects that i've zipped earlier.
    The situation is as follows:
    a RMI server zips a tree of Objects. The client side of the program tries to unzip the data and form it back to the Object (a DefaultMutableTreeNode) that is should be. However...
    The zip part goes without any problems. The unzipping however gives me a StreamCorruptedException.
    I have an object called ZipObject and it contains the size (int) of the zipped data and the size (int) of the uncompressed data. It also holds the data itself.
    my zip/unzip methods are as can be seen at:
    http://www.next-element.nl/~orchid/zip.html
    if anyone can help me...i'd be very grateful.
    thanx in advance.

    Oh yes i checked the ingoing and outgoing size of bytes...
    they are perfectly the same.
    The problem lies more in the in.readObject() method.
    when i dump the bytes that i receive to a File (which i do not want to do in the application) i can actually unzip it with unzip from my Linux system! But in my app. i don't write the objects to file...i just need the object back. but the data comes in clean.

  • Saving and loading serialized objects (StreamCorruptedException)

    Hello,
    I am relatively new to Serialization (coming to that, a bit new to Java too) and I am having a problem with the following:
    I am saving a number of serialized objects (all of the same class) in a file using the following way (the method is called multiple times to save a list of TeamMember objects):
    Note: TeamMember is a custom class.
    public void addTeamMember(TeamMember p) {
                outputStream = new ObjectOutputStream( new FileOutputStream( "team.dat", true ) );
                outputStream.writeObject( p );
                outputStream.flush();
                outputStream.close();
                outputStream = null;
    }Then I'm trying to retrieve the objects from the file and display them. The method used is the following (it will loop through the file until found or it throws an EOFException. Is using the EOFException good practice to search through the entire file?):
    public TeamMember getTeamMember(String id) {
            TeamMember currentMember = null;
            try {
                boolean found = false;           
                inputStream = new ObjectInputStream( new FileInputStream( "team.dat" ) );
                while ( !found ) {
                    currentMember = (TeamMember)inputStream.readObject();
                    if ( currentMember.getId().equals( id ) )
                        found = true;
                } // end while
                closeInputFile();
                return currentMember;
            } // end try
            catch ( EOFException e ) { // end of file reached
                closeInputFile();           
                return null;
            } // end catch
            catch ( IOException e ) {
                closeInputFile();
                System.err.println( e.getMessage() );
                return null;
            } // end catch
        }Now as a test, I am adding 3 members with IDs 1, 2 and 3 respectively. Then I am calling getTeamMember three times with the different IDs. With ID "1", it works fine. When I give it ID 2, it gives an IOException with message "StreamCorruptedException: invalid type code: AC".
    While tracing the program, I've seen that it always gives me that error when reading past the first object saved in the file.
    Am I saving the objects in a wrong way, or reading them is done incorrectly?
    Any help is much appreciated.
    I hope I was clear enough, and that I posted in the correct forum.
    Thanks in advance.
    Andrew.

    If that is so, might you hint me for a work around?
    I want to append objects in a single file, then be able to find and read an object from the file.
    Thanks again.
    Andrew

  • StreamCorruptedException - what is causing it?

    I am developing a networked multiplayer game in Java, but I am having problems when it comes to sending data around the network. The game will run fine for a seemingly random amount of time (usually between about 10 seconds and 2 minutes) before a StreamCorruptedException occurs in each of the clients. 90% of the time the message says "invalid type code: 00" but sometimes I get "invalid handle value" or various others.
    I have searched for ages for more information on this, but there isn't much help available. I have tried a couple of things suggested in other threads, to no avail.
    The code that listens for connections from clients:
    while(numConnections < MAX_CONNECTIONS) {
        socket = serverSocket.accept();
        numConnections++;
        System.out.println("Connection from " +socket.getInetAddress());
        ServerThread thread = new ServerThread(socket);+
        thread.start();
    }The ServerThread class handles each connection and contains the following method which is used to send objects to all connected clients:+
    public static void sendToClients(Object o) {
        try {
            for(int i = 0; i < connections.size(); i++) {
                ServerThread thread = connections.elementAt(i);
                thread.out.writeObject(o);
                thread.out.flush();
    catch(IOException e) {
        e.printStackTrace();
    }The Client class reads the objects sent by the server:
    try {
                Object o;
                while(true) {
                    o = inputStream.readObject();
    }The exception occurs in the o = inputStream.readObject() line
    Sorry about the bad formatting... first post and for some reason the input box jumps all over the place when I'm typing so I can't see what's being written!
    Edited by: interdreamuk on Feb 23, 2010 9:48 AM

    No, I haven't seen AC yet... only one input and output stream is created per socket and used for the life of that socket. The most common code I get is 00, but I have also seen 23 and 79. I tried searching for a list of what the codes mean, but can't find much info about the causes of this exception at all really. I know it gets thrown when "Control information in the stream is inconsistent" according to the API, but that doesn't really help much.
    Also, after reading about this for hours, I changed writeObject to writeUnshared (just a shot in the dark really), which for some reason seems to have significantly increased the amount of time for which the application will run before the exception occurs.
    Edited by: interdreamuk on Feb 24, 2010 12:46 AM

  • StreamCorruptedException while using JWS

    Hello,
    I'm wanting to deploy the client of a client/server networked app in JWS, but for some reason I'm getting StreamCorruptedExceptions when I try to deserialize Objects contained in network messages. This doesn't happen when I run the app outside of JWS, so it appears to be some weird interaction with JMS. Here are all the details I can think of:
    The app is being distributed as one jar, including all libraries, by using the Fatjar plugin for Eclipse.
    I'm using Apache Tomcat v5.5.12 as the application server so that I can click a link in a browser to start the JWS app.
    I'm using ActiveMQ v4.0M3 as a JMS provider to handle passing messages across the network. (The same thing happens with ActiveMQ v3.2.1)
    This is the error print out:
    Caught: javax.jms.JMSException: Failed to build body from bytes. Reason: java.io.StreamCorruptedException
    javax.jms.JMSException: Failed to build body from bytes. Reason: java.io.StreamCorruptedException
         at org.activemq.util.JMSExceptionSupport.create(JMSExceptionSupport.java:34)
         at org.activemq.command.ActiveMQObjectMessage.getObject(ActiveMQObjectMessage.java:173)
         at com.shai.ogma.networking.JMSLink.onMessage(JMSLink.java:115)
         at org.activemq.ActiveMQMessageConsumer.dispatch(ActiveMQMessageConsumer.java:703)
         at org.activemq.ActiveMQSessionExecutor.dispatch(ActiveMQSessionExecutor.java:95)
         at org.activemq.ActiveMQSessionExecutor.iterate(ActiveMQSessionExecutor.java:148)
         at org.activemq.thread.SimpleTaskRunner.runTask(SimpleTaskRunner.java:129)
         at org.activemq.thread.SimpleTaskRunner.access$100(SimpleTaskRunner.java:44)
         at org.activemq.thread.SimpleTaskRunner$1.run(SimpleTaskRunner.java:62)
         at edu.emory.mathcs.backport.java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:643)
         at edu.emory.mathcs.backport.java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:668)
         at java.lang.Thread.run(Unknown Source)
    Caused by: java.io.StreamCorruptedException
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readObject(Unknown Source)
         at java.util.HashMap.readObject(Unknown Source)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at java.io.ObjectStreamClass.invokeReadObject(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readObject(Unknown Source)
         at java.util.HashMap.readObject(Unknown Source)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at java.io.ObjectStreamClass.invokeReadObject(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readObject(Unknown Source)
         at java.util.HashMap.readObject(Unknown Source)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at java.io.ObjectStreamClass.invokeReadObject(Unknown Source)
         at java.io.ObjectInputStream.readSerialData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readObject(Unknown Source)
         at com.shai.ogma.messaging.OgmaMessage.readExternal(OgmaMessage.java:245)
         at java.io.ObjectInputStream.readExternalData(Unknown Source)
         at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
         at java.io.ObjectInputStream.readObject0(Unknown Source)
         at java.io.ObjectInputStream.readObject(Unknown Source)
         at org.activemq.command.ActiveMQObjectMessage.getObject(ActiveMQObjectMessage.java:167)
         ... 10 more
    Notes about the error message:
    The thing it is getting stuck on while trying to deserialize is one of my own classes with readObject() and writeObject() defined.
    It can serialize/deserialize without problems outside of JWS.
    All the classes I'm serializing are in synch between the server and the client. I.e. there shouldn't be any problems with serialversionUID caused by code being at different versions.
    The code at org.activemq.command.ActiveMQObjectMessage.getObject(ActiveMQObjectMessage.java:167) doesn't appear to be doing anything funny.
    Does anyone have any clues what might be causing this behavior and how to fix it?
    Thanks!

    Here is my guess. The browser VM has some subtle interractions with the browser. An SSL connection usually starts with the server sending a certificate and the client 'accepting it'. The acceptance or rejection is based on the root certificates configured in the client. The browser has such a 'database' of root certificates. I bet the browser VM is using the same database as the browser.
    When you run the application stand-alone, the database is somewhere in the JRE. Somehow the root certificate of your server certificate is not there.

  • StreamCorruptedException

    Hi,
    I'm trying to send serialized objects over socket connection, see the code snippet below.
    import java.io.*;
    import java.net.*;
    public class Test2 {
    private ObjectOutputStream oos;
    private ObjectInputStream ois;
    private Socket s;
    public Test2(String host, int port) {
         try {
         s = new Socket(host, port);
         s.setTcpNoDelay(true);
         oos = new ObjectOutputStream(s.getOutputStream());
         ois = new ObjectInputStream(s.getInputStream());
         oos.writeObject("data");
         oos.flush();
         System.out.println(ois.readObject());
         } catch (UnknownHostException e) {
         e.printStackTrace();
         } catch (IOException ioe) {
         ioe.printStackTrace();
         } catch (ClassNotFoundException cnfe) {
         cnfe.printStackTrace();
    public static void main(String args[]) {
         Test2 t = new Test2("localhost", 5000);
    When I compiled the program, I got the following error message,
    java.io.StreamCorruptedException: invalid stream header
    at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
    at java.io.ObjectInputStream.<init>(Unknown Source)
    at Test2.<init>(Test2.java:17)
    at Test2.main(Test2.java:63)
    Can someone give pointers on how to solve this problem?
    Thank you in advance for your help!

    If the other end isn't written in Java using ObjectInput/OutputStreams you can't use Serialization in either direction.

  • StreamCorruptedException in ObjectInputStream

    Hello!! I have a problem with serialization and ObjectInputStream/ObjectOutputStream classes:
    I have two programs. The first program writes objects in a file. Here is the code:
    FileOutputStream f = new FileOutputStream ("filename", true);
    ObjectOutputStream o = new ObjectOutputStream (f);
    o.writeObject (objetTest);
    f.close();
    o.close();
    The other program reads these objects:
    FileInputStream f = new FileInputStream ("filename");
    ObjectInputStream o = new ObjectInputStream (f);
    TestClass objetTest = (TestClass)o.readObject();
    f.close();
    o.close();
    The first program is executed and when it finishes the second program is executed. Imagine that the first program writes two object and the second program wants to read these two objects. The second program reading the first object runs ok, but when try to read the second object a java.io.StreamCorruptedException appears
    Anybody can help me? Any ideas?
    Cheers
    Kike

    A newly created ObjectOutputStream first writes a header to its encapsulated
    OutputStream. From your code I see that you're using the FileOutputStream
    in 'append mode'. So, if you write two objects, running the above code twice,
    you basically get this in your file: <header><object><header><object>.
    You're just using one ObjectInputStream; when it gets created it reads the
    header and then attempts to read objects from the encapsulated InputStream.
    It encounters another header when it attempts to read a second object,
    hence the StreamCorruptedException.
    kind regards,
    Jos

Maybe you are looking for