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

Similar Messages

  • StreamCorruptedException when reading from an ObjectInputStream

    Hello folks!
    I hope there's someone out there who can help me.
    I try to write a client-server-communication (via sockets). When starting the application I get the following exception:
    java.io.StreamCorruptedException: Type code out of range, is -84
         at java.io.ObjectInputStream.peekCode(Unknown Source)
         at java.io.ObjectInputStream.refill(Unknown Source)
         at java.io.ObjectInputStream.readObject(Unknown Source)
         at java.io.ObjectInputStream.readObject(Unknown Source)
         at com.sap.swf.protegecontrol.mcd.communication.StateTestClient.connect(StateTestClient.java:86)
         at com.sap.swf.protegecontrol.mcd.communication.StateTestClient.run(StateTestClient.java:42)
         at java.lang.Thread.run(Unknown Source)
    I tried several suggestions from several other threads, but nothing worked for me.
    Here's the excerpt of my coding:
    public void connect() {
    while (newConnectionRequested) {
    listening = true;
    Socket client = null;
    ObjectOutputStream oos = null;
    ObjectInputStream ois = null;
    Object input = null;
    try {
    client = new Socket(this.server, this.port);
    oos = new ObjectOutputStream(client.getOutputStream());
    catch (Exception e) {
    e.printStackTrace();
    System.exit(1);
    System.out.println("New connection requested by client");
    try {
    oos.writeObject(new StateRequestInfo());
    oos.flush();
    catch (Exception e) {
    e.printStackTrace();
    try {
    ois = new ObjectInputStream(client.getInputStream());
    catch (Exception e) {
    e.printStackTrace();
    while (listening) {
    try {
    input = ois.readObject();
    catch (Exception e) {
    e.printStackTrace();
    System.exit(0);
    if (input != null) {
    Display display = Mcd.getDisplay();
    if (input instanceof String) {
    System.out.println((String)input);
    if (input instanceof StateInfo) {
    this.state = (StateInfo)input;
    if (display != null) {
    display.syncExec(new Runnable() {
    public void run() {
    Mcd.getGUIInstance().setState(state);
    packagesReceived++;
    if (packagesReceived == this.END_VAL) {
    listening = false;
    packagesReceived = 0;
    try {
    oos.close();
    ois.close();
    client.close();
    catch (Exception e) {
    e.printStackTrace();
    System.out.println("Connection terminated by client");
    toLive++;
    if (toLive == this.END_APP) {
    newConnectionRequested = false;
    System.out.println("Client loop ended!");
    Comment: The method opens a new client socket, connects to the server and sends a StateRequestInfo-object to inform the server which type of communication is preferred. The "state"-communication should work as follows: the server sends StateInfo-objects until the client closes (when received a certain amount of packages) and re-opens connection -
    this runs in an endless loop in a separate threaad.
    The State-Info Object is quite large, because it contains a Vector which contains multiple objects of state-information concerning another part of the application. All self-written objects are serializable.
    I hope that's enough info. Thanks in advance.

    The solution for me was to create a new
    ObjectInputStream for each read, which will then
    expect:
    header | bob | header | dougThanks for the hint, but I tried this already and it didn't fix anything.
    An alternative is to skip 4 bytes (the length of the
    header) after each read, but that may not work well
    with socket streams.This can't be the solution because the StreamCorruptedException is also thrown when receiving the first object - that's why I think skipping the header after receiving the first StateInfo wouldn't fix anything.
    But thanks for your efforts!
    By the way, that's an excerpt of the server-code:
    public void run() {
    ObjectOutputStream out = null;
    long currtime;
    while (sending) {
    out = null;
    try {
    out = new ObjectOutputStream(client.getOutputStream());
    catch (Exception e) {
    // e.printStackTrace();
    if (out == null) {
    System.out.println("Connection terminated by client");
    break;
    currtime = System.currentTimeMillis();
    if (currtime > (reftime + this.TIME_INC)) {
    System.out.println("Sending data...");
    try{
    out.writeObject(theManagerInfo.getStateManager().getStateInfo());
    out.flush();
    catch(Exception e){
    reftime = currtime;
    try {
    if(out != null){
    out.close();
    client.close();
    catch (Exception e) {
    e.printStackTrace();
    Comment: the server runs in a separate thread and sends periodically StateInfo-Objects to the client that requestet the socket communication.
    Having received a certain amount of StateInfos the client automatically curts the link and requests a new communication

  • Strange StreamCorruptedException while using ObjectInputStream

    I have a strange problem:
    I am producing a java client which communication behaviour should be identical to a java applet (running in a web browser). I have the source code for the applet and I experience no problems running the applet.
    However when writing a stand alone communication class the code works fine for smaller Objects that are serialised but larger objects will not work!
    I have tried several objects in order to test the bevaiour and there is nothing in my code that would explain why certain objects (large ones) should fail. Due to licensing I am unfortunately unable to provide you with the source code (sorry)
    My client uses raw socket communication (basically objectinputstream connected to the inputstream delivered by the socket (all web reply removed so that the OIS is opened where it should be)) compared to the inputstream retrieved form an URLConnection in the applet.
    In both cases the communication is over HTTPS.
    So my question is:
    Is there a fundamental difference (on the byte streams) received
    1) From an URLConnection provided by the browser envirionment to the applet
    2) Directly from a socket class.
    How else would you explain the difference?
    Many thanks
    /Chris

    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: 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

  • Java.io.StreamCorruptedException: InputStream does not contain a serialized object

              I have an applet which calls a JSP to write data object to the db and then the
              JSP sends back the updated data object. The writing part is ok but the response
              is giving the following error. The data object is in a separate class which implements
              Serialized.
              Here's the code in the applet calling the JSP and the response from the JSP
              URL server = null;
              String urlConnectionString = "http://localhost:7001/isLoginValid.jsp";
              try
              server = new URL(urlConnectionString);
              catch(MalformedURLException e)
              System.out.println("URL exception: " + e );
              // send request
              ObjectInputStream response = null;
              Object result = null;
              try
              URLConnection conn = server.openConnection();
              conn.setDoOutput(true);
              conn.setUseCaches(false);
              conn.setRequestProperty("Content-Type", "application/octet-stream");
              ObjectOutputStream request = new ObjectOutputStream(new
              BufferedOutputStream(conn.getOutputStream()));
              request.writeObject((Object)dvo);
              request.flush();
              request.close();
              // get the result input stream
              response = new ObjectInputStream(new BufferedInputStream
              (conn.getInputStream()));
              // read response back from the server
              result = response.readObject();
              if( result!=null && (result instanceof DataVO))
              dvo = (DataVO)result;
              String vo = dvo.printDataVO();
              System.out.println("*DataVO*\n"+vo);
              else
              System.out.println("not an instanceof DataVO");
              catch(IOException ignored)
              System.out.println("Error in DataVO response");
              ignored.printStackTrace();
              Here's the code in the JSP sending the response back to the applet. The 'dvo'
              object is the object which is serialized and has gets and sets for the diff. data
              elements. When I print the 'dvo' before writing the object to outputStream it
              prints the correct values for the data element.
              // send response
              response.setStatus(HttpServletResponse.SC_OK);
              ObjectOutputStream outputStream = new ObjectOutputStream (new BufferedOutputStream
              (response.getOutputStream()));
              outputStream.writeObject(dvo);
              outputStream.flush();
              ERROR is as follows:
              Error in DataVO response
              java.io.StreamCorruptedException: InputStream does not contain a serialized object
              at java/io/ObjectInputStream.readStreamHeader
              at java/io/ObjectInputStream.<init>
              What am I doing wrong?. Please respond soon. The applet is run on IIS and the
              JSP in on weblogic 6.1. I'm not sure if that makes any difference.
              

              I have an applet which calls a JSP to write data object to the db and then the
              JSP sends back the updated data object. The writing part is ok but the response
              is giving the following error. The data object is in a separate class which implements
              Serialized.
              Here's the code in the applet calling the JSP and the response from the JSP
              URL server = null;
              String urlConnectionString = "http://localhost:7001/isLoginValid.jsp";
              try
              server = new URL(urlConnectionString);
              catch(MalformedURLException e)
              System.out.println("URL exception: " + e );
              // send request
              ObjectInputStream response = null;
              Object result = null;
              try
              URLConnection conn = server.openConnection();
              conn.setDoOutput(true);
              conn.setUseCaches(false);
              conn.setRequestProperty("Content-Type", "application/octet-stream");
              ObjectOutputStream request = new ObjectOutputStream(new
              BufferedOutputStream(conn.getOutputStream()));
              request.writeObject((Object)dvo);
              request.flush();
              request.close();
              // get the result input stream
              response = new ObjectInputStream(new BufferedInputStream
              (conn.getInputStream()));
              // read response back from the server
              result = response.readObject();
              if( result!=null && (result instanceof DataVO))
              dvo = (DataVO)result;
              String vo = dvo.printDataVO();
              System.out.println("*DataVO*\n"+vo);
              else
              System.out.println("not an instanceof DataVO");
              catch(IOException ignored)
              System.out.println("Error in DataVO response");
              ignored.printStackTrace();
              Here's the code in the JSP sending the response back to the applet. The 'dvo'
              object is the object which is serialized and has gets and sets for the diff. data
              elements. When I print the 'dvo' before writing the object to outputStream it
              prints the correct values for the data element.
              // send response
              response.setStatus(HttpServletResponse.SC_OK);
              ObjectOutputStream outputStream = new ObjectOutputStream (new BufferedOutputStream
              (response.getOutputStream()));
              outputStream.writeObject(dvo);
              outputStream.flush();
              ERROR is as follows:
              Error in DataVO response
              java.io.StreamCorruptedException: InputStream does not contain a serialized object
              at java/io/ObjectInputStream.readStreamHeader
              at java/io/ObjectInputStream.<init>
              What am I doing wrong?. Please respond soon. The applet is run on IIS and the
              JSP in on weblogic 6.1. I'm not sure if that makes any difference.
              

  • [java.nio] StreamCorruptedException when deserializing objects

    Hello everybody!
    I made a messaging (chat) program using java.io where all the client-server communication is done by serializing small objects. Now I would like to covert the server side to the NIO concept and I'm already struck. I successfully pass objects to the client and the client deserializes them, but only the first one! When it try to read the second it fails with a StreamCorruptedException.
    Here�s a sample (testing) code. In the server run() method I first serialize a string, then get its byte array from ByteArrayOutputStream and in the loop periodically send this byte array through the channel. On the client side I just read the deserialized object.
    Server run():
    public void run() {
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(baos);
                oos.writeObject("abcdefgh");
                byte[] objectArr = baos.toByteArray();
                baos.close();
                oos.close();
                ByteBuffer buff = ByteBuffer.allocate(objectArr.length);
                buff.put(objectArr);
                buff.flip();
                while(true) {
                    selector.select();
                    Set keys = selector.selectedKeys();
                    for (Object o : keys) {
                        SelectionKey key = (SelectionKey)o;
                        if (key.isAcceptable()) {
                            ServerSocketChannel server = (ServerSocketChannel) key.channel();
                            clientChannel = server.accept();
                            if (clientChannel == null)
                                continue;
                            clientChannel.configureBlocking(false);
                            SelectionKey clientKey = clientChannel.register(selector, SelectionKey.OP_WRITE);
                        } else if (key.isWritable()) {
                            SocketChannel client = (SocketChannel) key.channel();
                            if (buff.hasRemaining()) {
                                client.write(buff);
                            } else {
                                buff.clear();
                                buff.put(objectArr);
                                buff.flip();
                    try {
                        Thread.currentThread().sleep(2000);
                    } catch (InterruptedException e) {
                        return;
            } catch (IOException e) {
                e.printStackTrace();
        }Client run():
    public void run() {
            try {
                soc = new Socket("localhost", 4000);
                ObjectInputStream ois = new ObjectInputStream(soc.getInputStream());
                while(true) {
                    Object d = ois.readObject();
                    System.out.println("data = " + d.toString());
            } catch (Exception ex) {
                ex.printStackTrace();
        }At the second read I get a StreamCorruptedException.
    Apart from this I would like some hints in how to implement the application with NIO. For example how can I tell the objects apart on the client side � should I send every time a byte array before the object, which tells the length of the next coming object? This is probably not a 100% bulletproof solution and presents additional data transfer?
    Than you in advance!

    OK, I found a solution but I don't like it, because I don't understand it.
    The ObjectOutputStream adds a header (4 bytes) to the stream - if I send the array with those four bytes I get an StreamCorruptedException. If I send the array without the header I also get a StreamCorruptedException: "invalid stream header".
    If I reconstruct the object, by calling ObjectOutputStream.writeObject() and get it's byte array from ByteArrayOutputStream.toByteArray(), every time I have to fill the ByteBuffer, then it works.
    Here's the modified sending block, for the above example:
    } else if (key.isWritable()) {
                            SocketChannel client = (SocketChannel) key.channel();
                            if (buff.hasRemaining()) {
                                client.write(buff);
                            } else {
                                //* ---- added code ---------
                                baos.reset();
                                oos.writeObject("abcdefgh");
                                objectArr = baos.toByteArray();
                                buff.clear();
                                buff.put(objectArr);
                                buff.flip();
                        }   I really don't understand why I have to write the object in the object stream every time. I used ObjectOS and ByteArrayOS, to get the object byte array and then I thought I could forget about those streams and use this array to fill the ByteBuffer. What changes if I send the object through this process with every iteration (and how this harms speed - it's like sending everything twice)? If someone would explain this to me I would appreciate it much.

  • Can't use custom ClassLoader with ObjectInputStream

    Hi all,
    I want to transmit an object whose class is unknown to the receiver and whose class may not be loaded. Of course when the inputstream's readObject method tries to receive this class, it fails with a ClassNotFoundException. I have a custom FileClassLoader to dynamically load classes, this is tested and works.
    I can dynamically load this class and prove that the class was loaded by calling class.newInstance() from the loader.loadClass method. But then when I try to read that same class from the input stream, it says ClassNotFoundException!
    The code snippet looks like this:
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    FileClassLoader loader = new FileClassLoader(classFolder);
    Class L = loader.loadClass(className); // no .class at end
    System.out.println("New Instance "+L.newInstance().toString()); // works
    ObjectInputStream eventStream = ... // stream from a socket
    eventStream.readObject(); // throws class not found exception!
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    The only thing I can think is that the input stream only looks for classes loaded by the system classloader, could that be true? What other possibilities are there?
    If this is more appropriate for another forum just let me know and I'll post it there.
    Thanks in advance for any helpful hints anybody has!

    I was thinking of something along the lines of
    ObjectInputStream eventStream = (ObjectInputStream)Class.forName("java.io.ObjectInputStream", true, loader).newInstance();Of course, you would really have to get the proper Constructor for the class - and that just gets too long and stupid. Besides, I actually tried my suggestion, and it didn't work. I also tried setting the ContextClassLoader for the current thread (and creating a new thread with the ContextClassLoader set to "loader"). None of that works. Just setting the ContextClassLoader does not make the thread use it implicitly, it's apparently just a way to pass another ClassLoader to a thread, but it still needs to be used explicitly in a Class.forName call.
    I did, however, try David's suggestions of overriding resolveClass in ObjectInputStream. That worked fine! Here's what I created:
    import java.net.URLClassLoader;
    import java.io.InputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectStreamClass;
    import java.io.StreamCorruptedException;
    public class MyObjectInputStream extends java.io.ObjectInputStream
        URLClassLoader myLoader = null;
        public MyObjectInputStream(URLClassLoader newLoader, InputStream theStream) throws IOException, StreamCorruptedException
            super(theStream);
            myLoader = newLoader;
        protected Class resolveClass(ObjectStreamClass osc) throws IOException, ClassNotFoundException
            System.out.println("Hey, I'm in my resolveClass");
            Class theClass = null;
            try
                theClass = Class.forName(osc.getName(), true, myLoader);
            catch (Exception e)
                System.err.println("An Error in my ResolveClass:");
                e.printStackTrace();
            return theClass;
    }You then just create your ObjectInputStream with
    ObjectInputStream eventStream = new MyObjectInputStream(loader, theSocket.getInputStream());

  • 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?

  • 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.

  • 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

  • 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 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 deserializing in method getClassDesc

    I�m serializing a class, sending from a servlet to an applet, and when I deserialize the class inside the browser I get a StreamCorruptedException, in the method getClassDesc. But when I run (or debug) the applet inside my IDE (NetBeans) the deserializing process works OK. I'm thinking in a classpath problem, but I have revised the classes used in the serialized class and I put all of them in the applet jar file.
    The process only fails with a concrete class deserialization, I know the process is OK because can send another objects without problem, same in the browser than in the IDE. The problem is with the object with more size, I don't know about limits, but I download the entire object in a byte array before, then I decompress and deserialize.
    Any clues?

    Hi, try clear your stream before writing any objects to it.
    (ObjectOutputStream.flush())
    This is nessary to avoid that Headerinformatons will be
    joined with the object, which appears to be corrupt for the
    ObjectInputStream if this happens.
    Hope this helps.
    Greetings Michael

Maybe you are looking for

  • KE33 report main data  and Line items in KE33 doesn't match

    < MODERATOR:  Message locked.  Please post this message in the [Controlling forum|SAP ERP Financials - Controlling;. > All, I have created COPA report (cost based COPA).  When I ran the report, I have 5 line items and a total row.  When selected one

  • After upgrading from it6 to itunes7 my videos doesn´t work

    After upgrading from itunes6 to itunes7 my videos doesn´t work. Theres no error message, no reaction. all the music play like befor, only my vids (quicktime), all!! the vids doesnt work after updating..i hope, that someone could help me.. Many thanks

  • RFC to JDBC Empty tables parameters in response

    Hello, I've got a problem with an XI query (RFC to JDBC, UPDATE_INSERT) which contains a "tables" parameter. When I get the RFC's response in se37 (in the calling system of course), the "tables" parameter is empty. I need the values for further proce

  • Copy and paste images and viewing them

    I just started using DW MX2004 to build ebay ads, but I am needing to copy and paste hosted images into the template and view them in design view. I am not using a server of any sort, just designing. When I copy and paste a hosted image into DW I wou

  • REPORT ON JOB ARCHITECTURE

    Hi Experts. Do we have any report available from which we can get the upward mobility of an employee in the Job Architecture? Eg. If the HR Manager wants to know that how many people have grown from "Field Sales" to "Manager Sales"?  So , do we have