ObjectInputStream readObject loop

When using the readObject method of ObjectInputStream the method blocks until it reads something from the stream.
how would i put this method in a test loop?
as when the method blocks and is waiting to read, if the output stream at the other end of the socket closes, then an IOException will be thrown.
is there something i can write like, while(input != EOF)?
cheers

There is no object that a readObject call could return to indicate that it was at end of file. On files the available method lets you know when no more data is available, this method can't be used with sockets since the sender may pause between objects. If the sender closes a Socket Exception: Connection reset will be thrown, you can catch this and terminate. A better choice is to define an object that meand end of transmission. But this is not always feasible, if you must be able to send any arbitrary object.
Here's an example of a simple object transfer
Sending class:
import java.io.*;
import java.net.*;
import java.util.*;
public class TestWO
     static public void main(String [] args)
          Socket sock;
          ObjectOutputStream oos;
          try
               sock = new Socket("127.0.0.1",5050);
               oos = new ObjectOutputStream(sock.getOutputStream());
               for(int i = 0; i<args.length; i++)
                    Thread.sleep(2000);
                    System.out.println("writing "+args);
                    oos.writeObject(args[i]);
          catch(Exception e){System.out.println(e);}
Receiving class:
import java.io.*;
import java.net.*;
import java.util.*;
public class TestRO
     Socket sock;
     ObjectInputStream ois;
     ServerSocket ss;
     private void listen(int port)
          System.out.println("Listening on port="+port);
          try
               ss = new ServerSocket(port);
               sock = ss.accept();
               System.out.println("call accepted");
               ss.close();
               receive();
          catch(Exception e){     e.printStackTrace();}
     static public void main(String [] args)
          new TestRO().listen(5050);
     void receive()
          System.out.println("starting receiver");
          try
               ois = new ObjectInputStream(sock.getInputStream());
          catch(IOException e)
               System.out.println(e);
               return;
          boolean running = true;
          Object obj;
          while(running)
               try
                    obj = ois.readObject();
                    System.out.println("object="+obj);
               catch(SocketException e)
                    if(e.getMessage().equals("Connection reset")){System.out.println("closed by partner");}
                    else e.printStackTrace();
                    running = false;
               catch(Exception ex){ex.printStackTrace(); running = false;}
          try
               ois.close();
               sock.close();
          catch(Exception e){}

Similar Messages

  • Tuning the performance of ObjectInputStream.readObject()

    I'm using JWorks, which roughly corresponds to jdk1.1.8, on my client (VxWorks) and jdk1.4.2 on the server side (Windows, Tomcat).
    I'm serializing a big vector and compressing it using GZipOutputStream on the server side and doing the reverse on the client side to recreate the objects.
    Server side:
    Vector v = new Vector(50000);//also filled with 50k different MyObject instances
    ObjectOutputStream oos = new ObjectOutputStream(new GZipOutputStream(socket.getOutputStream()));
    oos.writeObject(v);Client side:
    ObjectInputStream ois = new ObjectInputStream(new GZipInputStream(socket.getInputStream()));
    Vector v = (Vector)ois.readObject();ObjectInputStream.readObject() at the client takes a long time (50secs) to complete, which is understandable as the client is a PIII-700MHz and the uncompressed vector is around 10MB. Now the problem is that because my Java thread runs with real time priority (which is the default on Vxworks) and deprive other threads, including non-Java ones, for this whole 50 sec period. This causes a watchdog thread to reset the system. I guess most of this delay is in GZipInputStream, as part of the un-gzipping process.
    My question is, is there a way to make ObjectInputStream.readObject() or any of the other connected streams (gzip and socket) yield the CPU to other threads once in a while? Or is there any other way to deal with the situation?
    Is the following a good solution?
    class MyGZipInputStream extends GZipInputStream {
        public int count = 0;
        public int read(byte b[], int off, int len) throws IOException {
             if(++count %10 == 0) // to avoid too many yields
                  Thread.yield();
              return super.read(b, off,len);
    }Thanks
    --kannan                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    I'd be inclined to put the yielding input stream as close to the incoming data as possible - thus avoiding any risk that time taken to read in data and buffer it will cause the watchdog to trip.I could do that. But as I'm doing Thread.yield only once every x times, would it help much?
    Also, as I've now found out, Thread.yield() wouldn't give other low priority tasks a chance to run. So I've switched to Thread.sleep(100) now, even though it could mean a performance hit.
    Another relaed question - MyGzipStream.read(byte[], int, int) is called about 3million times during the readObject() of my 10MB vector. This would mean that ObjectInputStream is using very small buffer size. Is there a way to increase it, other than overriding read() to call super.read() with a bigger buffer and then doing a System.arrayCopy()?
    Thanks
    --kannan                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • How ObjectInputStream.readObject() works??

    Below is Test.java, some codes on simple serialization operations (copied from a book.) A "Blip1" object is created, serialized to a file, then deserialized back from the file. Everything works fine!!
    My question is, why does the last line work, "b1 = (Blip1)in.readObject();" ?
    I mean, ObjectInputStream is part of [package java.io], how can we create a "Blip1" object of [package anypackage] while we are inside [package java.io]?? Am I missing something fundamental?
    I thought this ObjectInputStream.readObject() is based on Reflection, that is, ObjectInputStream.readObject() created the "Blip1" object based on the class name. So I wrote Creator.java (see below) and the result was an IllegalAccessException --- we cannot create a "Blip1" object while we are inside another package. This shows that ObjectInputStream.readObject() is not really based on Reflection(??)
    How does ObjectInputStream.readObject() work??
    //Test.java
    package anypackage;
    class Blip1 implements Externalizable {
      public Blip1() {System.out.println("Blip1 created");}
      public void writeExternal(ObjectOutput out) throws IOException {}
      public void readExternal(ObjectInput in)
        throws IOException, ClassNotFoundException {}
    public class Test {
      public static void main(String[] args)
      throws IOException, ClassNotFoundException {
        System.out.println("Constructing objects:");
        Blip1 b1 = new Blip1();
        ObjectOutputStream o = new ObjectOutputStream(
          new FileOutputStream("Blips.out"));
        System.out.println("Saving objects:");
        o.writeObject(b1);
        o.close();
        // Now get them back:
        ObjectInputStream in =
          new ObjectInputStream(
            new FileInputStream("Blips.out"));
        System.out.println("Recovering b1:");
        b1 = (Blip1)in.readObject();
    //Creator.java
    package anyotherpackage;
    import java.util.*;
    public class Creator{
      Object o;
      public Creator(){
        try{
          Class c = Class.forName("anypackage.Blip1");
          Object o = c.newInstance();
        } catch (Exception e){
          System.out.println(e);
      public static void main(String[] args){
        Creator c = new Creator();
    }

    As far as i understand the ObjectInputStream.readObject() create object by recursively building the memory owned by the object, obviously object Ctor is not called (otherwise serializeable classes were forced to have empty Ctor).
    It goes like this -
    1)when object implements Serializable interface its stream hold description of the the object memory (for each datamember we will have something like offset,datamember type, and streamed datamember), ObjectInputStream.readObject build the datamembers recursively (recursion is stopped when we have primitive type datamember)
    2)when object implements Externalizable interface the programmer is responsible to stream object's datamembers to the ObjectOutput and to read them from the ObjectInput, ObjectInputStream is responsible to create an empty object for you
    anyway no Ctors are involved

  • 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

  • Print all lines in ObjectInputStream

    Hi All,
    I finally got this working to read data that was serialized back. I want to now see all the data. Right now I get one line printed out. I tried for loop and a while loop. Can not use Iterator. Any ideas? Thanks
    New to this and hoping for a little help to print all the data out.
    Sample code:
    import java.io.*;
    public class ReadFilePosition {
    public static void main(String[] args) throws ClassNotFoundException {
    PositionRequestMessage beamtrack = null;
    try {
    File file = new File("RDD_Position.bin");
    FileInputStream fileInputStream = new FileInputStream(file);
    BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
    ObjectInputStream objectInputStream = new ObjectInputStream(bufferedInputStream);
    Position ar = (Position)objectInputStream.readObject();
                   System.out.println("ActivityID: "+ ar.getPosition_azimuth()+" "+ar.getPosition_azimuth_rate()+" "+ar.getPosition_elevation_rate());
    } catch (Exception e) {
    System.out.println(e);
    System.exit(1);
    }

    Keep calling readObject() until you get an EOFException.

  • ObjectOutputStream.readObject

    I am writing a client server application which exchanges objects over a
    socket connection. A new thread is started for each client connection
    and
    ObjectInputStream.readObject is used to receive the object. Once this
    object is processed the server must check from more messages until it
    receives a disconnect message. I do this using the following code:
    while(disconnect!=true)
    try {
    SphinxMessage msg = (SphinxMessage)ois.readObject();
    this.processNormalMessage(msg);
    }catch(IOException e3) { /*do nothing*/ }
    catch (ClassNotFoundException cnfe2){
    System.out.println(" readobject cnfe");
    cnfe2.printStackTrace();
    How can i make ObjectInputStream.readObject() block until it receives
    a message because at the moment it is continously looping calling
    readObject and catching the exception.
    Any help or suggestions would be appreciated.
    David.

    Once this object is processed the server must check from more messages until it
    receives a disconnect messageFWIW, from looking at posted code, here are my comments:
    1) What does a disconnect message look like?
    2) Is this disconnect message processed by this.processNormalMessage(msg);
    -- if so, did it correctly set the variable disconnect to false so that you can break out of the loop
    (I don't see this variable being set to false inside of the loop)?
    3) Have you tried to add a e3.printStackTrace(); to see what the IOException is?
    V.V.

  • ObjectInputStream anomilies...please help

    Hi,
    I have been having some trouble with reading from a socket using ObjectInputStream.readObject(). I have two versions of my code, just one line different. In the first version, the first time through the loop I read perfectly, then all times after that I read nothing. In the second version, I also read perfect the first time through the loop, but every subsequent time I don't read the new stuff, it tells me I am reading the same thing that it read the first time. Here is the code and some output:
    ArrayList remoteEvents = new ArrayList();
    while (running) {
            remoteEvents.clear();  //this is commented out in the other version of my code
            System.out.println("about to call readObject()");
            remoteEvents = (ArrayList)ois.readObject();
            System.out.println("received " + remoteEvents + " remote events");
    }Here is some output produced by the above code:
    about to call readObject()
    received [Jeff is great at 0.0, Jeff is great at 0.0] remote events
    about to call readObject()
    received [] remote events
    Now, here is the second version. In this one, I don't clear the ArrayList:
    ArrayList remoteEvents = new ArrayList();
    while (running) {
            //remoteEvents.clear();
            System.out.println("about to call readObject()");
            remoteEvents = (ArrayList)ois.readObject();
            System.out.println("received " + remoteEvents + " remote events");
    }Here is some output produced by this code:
    about to call readObject()
    received [Jeff is great at 0.0, Jeff is great at 0.0] remote events
    about to call readObject()
    received [Jeff is great at 0.0, Jeff is great at 0.0] remote events
    about to call readObject()
    received [Jeff is great at 0.0, Jeff is great at 0.0] remote events
    See, each subsequent time through the loop, what is being sent to this input stream changes. The first time, the messages were "[Jeff is great at 0.0, Jeff is great at 0.0]". The second time, they were
    "[Jeff is great at 0.011, Jeff is great at 0.011]". The third time they were "[Jeff is great at 0.022, Jeff is great at 0.022]" etc. Print statements at the sender verify that these different messages are being sent.
    So, it seems that if I do NOT clear the ArrayList then I always see the same messages in there, while if I clear it then I only see messages the first time.
    Anyone got any hints?
    Thanks,
    Jeff

    you have the similiar problems with this 1...
    http://forum.java.sun.com/thread.jsp?forum=31&thread=513011

  • ObjectInputStream - StringBuffer memory error

    Good day to all. My application has a memory problem. I ran hprof and found the two highest memory hogs to be
    TRACE 13569:
         java.lang.StringBuffer.toString(StringBuffer.java:1068)
         java.io.ObjectInputStream.readUTFBody(ObjectInputStream.java:2198)
         java.io.ObjectInputStream.readObject(ObjectInputStream.java:336)
         java.io.ObjectInputStream.inputArray(ObjectInputStream.java:1142)
    TRACE 13570:
         java.lang.StringBuffer.setLength(StringBuffer.java:258)
         java.io.ObjectInputStream.readUTFBody(ObjectInputStream.java:2199)
         java.io.ObjectInputStream.readObject(ObjectInputStream.java:336)
         java.io.ObjectInputStream.inputArray(ObjectInputStream.java:1142)I know there are problems in String Buffer (at least there used to be) To correct this should I change the version JVM I'm using or look deeper to see if something is holding on to the data that is being read?
    Thanks
    ST

    I'm sorry, I didn't quite understand your response. The post was not the error it was from profiling the application. Regardless, for future searches etc, I think that I have found the memory problem.
    If you read data, or store data, in a string buffer and then extract a small part of it (using substring for example) the section that you extract will be equal in size (memory) to the original string buffer.
    WHY?
    (This happened to me once before and it was a real bear to track down) In an effort to increase performance in java it was decided that if you want a substring of a string buffer you are returned a string pointing to the substring beginning and end points. This keeps the substring as reachable and therefore the memory grows. You can see this if you look at the source code for StringBuffer. So, if you are reading a large file and storing information found in that file you are storing more than you think. Here is the solution that I have used.
    // Inside a read loop.
    // Keep in mind that in my original post we were reading an object which reads into a StringBuffer hence this example.
    StringBuffer SB = new StringBuffer(myBufferedReader.readLine());
    // Find the data you are looking for, an IP for example.
    int ipStart = SB.indexOf(myIpFunction());
    String wholeIP = myIPExtractor(SB.substring(ipStart));
    // WholeIP is now only 15 chars long BUT it still points to the original
    // StringBuffer possibly thosands of chars long.
    // Store in a hashtable the wrong way.
    // This still points to the whole String Buffer......
    myHashtable.put(wholeIP,wholeIP);
    // My better way which adds methods BUT reduces overall memory.
    String toStore = String.copyValueOf(wholeIP.toCharArray[]);
    // You could, of course just store the char array too.Comments welcomed. I hope this helps someone else who finds a string buffer memory error in their application.

  • ObjectInputStream() returning null and EOFException - need help

    I have been working on this little snippet of code all day and I cannot understand why I get null values when I run a display application. The code is posted below for 3 file. PhoneList.java is for serialization. CreatePhoneList is to populate a saved file with phone numbers and names of contacts. DisplaySavedPhoneList.java is to display the saved names and numbers. I'm not looking for the correct code, put for someone to point me in the right direction on why I'm getting these results so I can find a solution.
    Here is the PhoneList class:
    import java.io.*;
    public class PhoneList implements Serializable
        private String name;
        private String num;
        private String phName;
        private String phNum;
        PhoneList(String phNum, String phName)
            setName(phName);
            setNum(phNum);
        public String getName()
            return phName;
        public String getNum()
            return phNum;
        public void setName(String phName)
            name = phName;
        public void setNum(String phNum)
            num = phNum;
    }Here is the CreatePhoneList class
    import java.io.*;
    import java.util.*;
    public class CreatePhoneList
        public static void main(String[] args) throws IOException
            ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("PhoneList.txt"));
            PhoneList list;
            String phName;
            String phNum;
            final String QUIT = "QUIT";
            Scanner in = new Scanner(System.in);
            System.out.println("Enter a phone number or " + QUIT + " to quit.");
            phNum = in.next();
            while(!phNum.equals(QUIT))
                System.out.println("Enter the contact name.");
                phName = in.next();
                list = new PhoneList(phNum, phName);
                output.writeObject(list);
                System.out.println("Enter a phone number or " + QUIT + " to quit.");
                phNum = in.next();
            output.close();
    }and this is the DisplaySavedPhoneList class:
    import java.io.*;
    import java.util.*;
    public class DisplaySavedPhoneList
        public static void main(String[] args) throws IOException, ClassNotFoundException
            ObjectInputStream input = new ObjectInputStream(new FileInputStream("PhoneList.txt"));
            PhoneList list;
            final int SHOW = 1;
            int showList;
            int count = 0;
            Scanner in = new Scanner(System.in);
            try
                System.out.print("To display Phone List enter " + SHOW);
                showList = in.nextInt();
                while(showList == SHOW)
                    list = (PhoneList)input.readObject();
                    System.out.println("Name: " + list.getName() + " Phone Number: " + list.getNum());
                    count++;
            catch(EOFException e)
                System.out.println("Oops, something broke!");
                input.close();
    }This is the result from running the DisplaySavedPhoneList application:
    To display Phone List enter 1
    1
    Name: null Phone Number: null
    Name: null Phone Number: null
    Oops, something broke!

    ok, I did that, and its pointing me to the line commented below. I did a practical exercise where the code was almost identical and it worked fine. The only difference are the variables.
    try
                System.out.print("To display Phone List enter " + SHOW);
                showList = in.nextInt();
                while(showList == SHOW)
                    list = (PhoneList)input.readObject(); //this is the line that was identified in the stacktrace
                    System.out.println("Name: " + list.getName() + " Phone Number: " + list.getNum());
                    count++;
            catch(EOFException e)
                System.out.println("Stack Trace");
                e.printStackTrace();
                input.close();
            }here is the total stack trace, in case you were wondering...
    To display Phone List enter 1
    1
    Name: null Phone Number: null
    java.io.EOFException
    Name: null Phone Number: null
    Stack Trace
            at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2554)
            at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1297)
            at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
            at DisplaySavedPhoneList.main(DisplaySavedPhoneList.java:21)I'm still not quite sure what this is telling me though.

  • NotActiveException when Using ObjectInputStream

    package serialization;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.NotActiveException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;
    public class Ser15OBJSTRTut3 implements Serializable
         int size;
         private Animal objAnimal;
         private int getSize()
              return size;
         private void setSize(int iSize)
              size=iSize;
         private void setAnimalInstance(Animal objAnimal)
              objAnimal=objAnimal;
         private Animal getAnimalInstance()
              return objAnimal;
          * Constructor
          * @param objAnimal
          * @param size
         public Ser15OBJSTRTut3(Animal objAnimal,int size)
              setAnimalInstance(objAnimal);
              setSize(size);
         public static void main(String[] args) {
              Animal objAnimal=new Animal();
              objAnimal.setAnimalSize(20);
                   Ser15OBJSTRTut3 objSer15OBJSTRTut3
                    =new Ser15OBJSTRTut3(objAnimal,40);
              try {
                   ObjectOutputStream objObjectOutputStream=
                          new ObjectOutputStream
                          (new FileOutputStream("C:\\STORE\\data.txt"));
                           objSer15OBJSTRTut3.writeObject
                           (objObjectOutputStream,objSer15OBJSTRTut3);
    //Control passes to  writeObject() below....
                   objObjectOutputStream.close();
              } catch (FileNotFoundException e) {
                   e.printStackTrace();
              } catch (IOException e) {
                   e.printStackTrace();
              // END OF WRITING PROCESS
                    // START READING THE SAME...
              try {
                   ObjectInputStream objectInputStream=
                           new ObjectInputStream
                           (new FileInputStream("C:\\STORE\\data.txt"));
                           Ser15OBJSTRTut3 obj2Ser15OBJSTRTut3=null;
                   objectInputStream.defaultReadObject();
                   System.out.println("DEFAULT="+objectInputStream.readInt());
                   obj2Ser15OBJSTRTut3=      (Ser15OBJSTRTut3)objectInputStream.readObject();
                   // I  NEED THE obj2Ser15OBJSTRTut3 Object back
                   System.out.println(obj2Ser15OBJSTRTut3.size);
                       System.out.println
    (obj2Ser15OBJSTRTut3.getAnimalInstance().getAnimalSize());
                         objectInputStream.close();
              } catch (FileNotFoundException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              } catch (ClassNotFoundException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
         //END OF DESERIALIZATION...
         public void writeObject( ObjectOutputStream objObjectOutputStream,Ser15OBJSTRTut3 objSer15OBJSTRTut3) throws IOException
              try
                   objObjectOutputStream.defaultWriteObject();
                   objObjectOutputStream.writeInt(objSer15OBJSTRTut3.getAnimalInstance().getAnimalSize());
              catch(IOException e)
                   e.printStackTrace();
    class Animal
         int size;
         public int getAnimalSize()
              return size;
         public void setAnimalSize(int iSize)
              size=iSize;
    O/P :
    java.io.NotActiveException: not in call to writeObject
         at java.io.ObjectOutputStream.defaultWriteObject(Unknown Source)
         at serialization.Ser15OBJSTRTut3.writeObject(Ser15OBJSTRTut3.java:86)
         at serialization.Ser15OBJSTRTut3.main(Ser15OBJSTRTut3.java:50)
    java.io.NotActiveException: not in call to readObject
         at java.io.ObjectInputStream.defaultReadObject(Unknown Source)
         at serialization.Ser15OBJSTRTut3.main(Ser15OBJSTRTut3.java:63)

    Read what the Javadoc says about that exception.
    objSer15OBJSTRTut3.writeObject
    (objObjectOutputStream,objSer15OBJSTRTut3); objOutputStream.writeObject(objSer15OBJSTRTut3);
    Ser15OBJSTRTut3 obj2Ser15OBJSTRTut3=null;
                   objectInputStream.defaultReadObject();Ser15OBJSTRTut3 obj2Ser15OBJSTRTut3 = (Ser15OBJSTRTut3)objectInputStream.readObject();
                   System.out.println("DEFAULT="+objectInputStream.readInt());You haven't written an int so this will fail with an EOFException.
                   obj2Ser15OBJSTRTut3= (Ser15OBJSTRTut3)objectInputStream.readObject();You haven't written a second instance of this either so ditto.
                   objObjectOutputStream.defaultWriteObject();OK
                   objObjectOutputStream.writeInt(objSer15OBJSTRTut3.getAnimalInstance().getAnimalSize());That 'int' will disappear inside the readObject() call above. If you want to read that, you have to write a custom readObject() method that reads it. But you don't need to, as the Animal's 'size' is already serialized for you.

  • EOF on readObject() in Applet

    I'm getting EOFException from ObjectInputStream.readObject() in an applet connecting to a servlet to get a serialized object. I've searched the web for the last couple days on this, and have tried a myriad of suggestions, no luck.
    The most relevant fix for the EOF is to set the content length header before sending from the servlet, but that hasn't helped.
    I'm starting to wonder if this may be a jvm incompatability -- the servlet is running under 1.3.1, and the applet is run under 1.5. Are there issues with serialization between jvms?

    Suppose that we have this private final RSAPrivateKey privateKey defined. And it is initialized in the private constructor/installer. How does the JC protect the memory of this variable? By the access modifier? i.e. private/public/..?The chip will most likely store the key in the crypto co-processor (this is up to the implementation though) which has higher tamper resistance etc. The applet firewall will logically protect the data in that no other applet context can access that memory. The visibility of the field will prevent other classes accessing it.
    I would like to know how does GSM achieve the protection of its card authentication key. We know that the key is never readable. The only way that you use it is through APDU "RUN_GSM_ALGORITHM". So how can we do the same through JavaCard??By not implementing a command that exposes the key. If you never return the bytes of the key and only expose methods/commands to use the key then no one can get your private key.
    - Shane

  • NullPointerException in java.io.ObjectInputStream.inputClassFields

    Randomly, while starting a managed server, the following exception is logged in the log files. What does it mean, and how can I resolve this.
    I am using Weblogic Server 7.0 Sp1 with JDK 1.3.1_08.
    Exception Trace:
    The WebLogic Server did not start up properly.
    Exception raised:
    java.lang.NullPointerException
    at java.io.ObjectInputStream.inputClassFields(ObjectInputStream.java:2266)
    at java.io.ObjectInputStream.defaultReadObject(ObjectInputStream.java:514)
    at weblogic.management.internal.DynamicMBeanImpl.readObject(DynamicMBeanImpl.java:2167)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.io.ObjectInputStream.invokeObjectReader(ObjectInputStream.java:2209)
    at java.io.ObjectInputStream.inputObject(ObjectInputStream.java:1406)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:381)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:231)
    at java.util.ArrayList.readObject(ArrayList.java:526)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.io.ObjectInputStream.invokeObjectReader(ObjectInputStream.java:2209)
    at java.io.ObjectInputStream.inputObject(ObjectInputStream.java:1406)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:381)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:231)
    at weblogic.management.ManagedServerAdmin.bootstrapLocalServer(ManagedServerAdmin.java:214)
    at weblogic.management.ManagedServerAdmin.initialize(ManagedServerAdmin.java:122)
    at weblogic.t3.srvr.T3Srvr.initialize1(T3Srvr.java:659)
    at weblogic.t3.srvr.T3Srvr.initialize(T3Srvr.java:589)
    at weblogic.t3.srvr.T3Srvr.run(T3Srvr.java:277)
    at weblogic.Server.main(Server.java:32)
    --------------- nested within: ------------------
    weblogic.management.configuration.ConfigurationException: Exception encountered connecting to http://machine1:7001/wl_management_internal2/
    Bootstrap - with nested exception:
    [java.lang.NullPointerException]
    at weblogic.management.ManagedServerAdmin.bootstrapLocalServer(ManagedServerAdmin.java:235)
    at weblogic.management.ManagedServerAdmin.initialize(ManagedServerAdmin.java:122)
    at weblogic.t3.srvr.T3Srvr.initialize1(T3Srvr.java:659)
    at weblogic.t3.srvr.T3Srvr.initialize(T3Srvr.java:589)
    at weblogic.t3.srvr.T3Srvr.run(T3Srvr.java:277)
    at weblogic.Server.main(Server.java:32)
    Reason: Fatal initialization exception
    Throwable: weblogic.management.configuration.ConfigurationException: Exception encountered connecting to http://machine1:7001/wl_management
    _internal2/Bootstrap - with nested exception:
    [java.lang.NullPointerException]
    java.lang.NullPointerException
    at java.io.ObjectInputStream.inputClassFields(ObjectInputStream.java:2266)
    at java.io.ObjectInputStream.defaultReadObject(ObjectInputStream.java:514)
    at weblogic.management.internal.DynamicMBeanImpl.readObject(DynamicMBeanImpl.java:2167)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.io.ObjectInputStream.invokeObjectReader(ObjectInputStream.java:2209)
    at java.io.ObjectInputStream.inputObject(ObjectInputStream.java:1406)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:381)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:231)
    at java.util.ArrayList.readObject(ArrayList.java:526)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.io.ObjectInputStream.invokeObjectReader(ObjectInputStream.java:2209)
    at java.io.ObjectInputStream.inputObject(ObjectInputStream.java:1406)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:381)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:231)
    at weblogic.management.ManagedServerAdmin.bootstrapLocalServer(ManagedServerAdmin.java:214)
    at weblogic.management.ManagedServerAdmin.initialize(ManagedServerAdmin.java:122)
    at weblogic.t3.srvr.T3Srvr.initialize1(T3Srvr.java:659)
    at weblogic.t3.srvr.T3Srvr.initialize(T3Srvr.java:589)
    at weblogic.t3.srvr.T3Srvr.run(T3Srvr.java:277)
    at weblogic.Server.main(Server.java:32)
    --------------- nested within: ------------------
    weblogic.management.configuration.ConfigurationException: Exception encountered connecting to http://machine1:7001/wl_management_internal2/
    Bootstrap - with nested exception:
    [java.lang.NullPointerException]
    at weblogic.management.ManagedServerAdmin.bootstrapLocalServer(ManagedServerAdmin.java:235)
    at weblogic.management.ManagedServerAdmin.initialize(ManagedServerAdmin.java:122)
    at weblogic.t3.srvr.T3Srvr.initialize1(T3Srvr.java:659)
    at weblogic.t3.srvr.T3Srvr.initialize(T3Srvr.java:589)
    at weblogic.t3.srvr.T3Srvr.run(T3Srvr.java:277)
    at weblogic.Server.main(Server.java:32)
    Please provide some help.
    -Michael

    Thanks,
    I'm using AWT list - and viewing the applet through IE5 - i also have the java plugin.
    (If i place rt.jar in the archive of the .html file all works fine)
    However if not i keep getting the following error (as a print stack trace):
    java.lang.ClassNotFoundException
         at java/io/ObjectInputStream.loadClass0 (ObjectInputStream.java)
         at java/io/ObjectInputStream.resolveClass (ObjectInputStream.java)
         at java/io/ObjectInputStream.readClassDescriptor (ObjectInputStream.java)
         at java/io/ObjectInputStream.readNewObject (ObjectInputStream.java)
         at java/io/ObjectInputStream.readObject (ObjectInputStream.java)
         at java/io/ObjectInputStream.goToEndOfBlockData (ObjectInputStream.java)
         at java/io/ObjectInputStream.readNewObject (ObjectInputStream.java)
         at java/io/ObjectInputStream.readObject (ObjectInputStream.java)
         at Ticker/Ticker.getData (Ticker.java:205)
         at Ticker/Ticker.init (Ticker.java:159)
         at Ticker/TickerApplet.start (TickerApplet.java:199)
         at com/ms/applet/AppletPanel.securedCall0 (AppletPanel.java)
         at com/ms/applet/AppletPanel.securedCall (AppletPanel.java)
         at com/ms/applet/AppletPanel.processSentEvent (AppletPanel.java)
         at com/ms/applet/AppletPanel.run (AppletPanel.java)
         at java/lang/Thread.run (Thread.java)

  • ObjectInputStream.available() is zero

    Hi,
    i have a huge problem:
    i have my deserialization and the file that has to be deserialized in a package.
    When i add those source files to my workspace and run the application from eclipse, my ObjectInputStream has no bytes available, although it finds the resource.
    What could be the reason for that?
    Liz

    let me be more specific ,
    i guess you know the CubbyHole problem, where 2 different threads(producer/consumer) hold the same object(CubbyHole).
    now, suppose u have 2 objects CubyHole1 and CubbyHole2 which 2 different threads hold them . and you want to access both of them (in a sequential manner) but not to be blocked when you access each one of them .
    the operation that the CubbyHole does when accessing to it is : " ObjectInputStream.readObject() " .
    " ObjectInputStream.readObject() " is a blocking operation. as most of the programers would use some kind of available() method before accessing the CubyHole ,but available() always retur....... . so no such a solution is supplied by the Java Sun.(not that i have complains , they really did a great job with all the documentation....)
    I didn't invent the CubbyHole problem, this is a solution that is supplied and i use it. now u suggest me to
    take that CubyHole1 and CubyHole2 and make each one of them a thread !!!??!!
    well ,i don't think it should be the solution for a problem that can and should be solved by the Java Sun developers ( the available() issue ).
    anyway , if there is no other choise (except for the third solution that i suggested and the ugliest one) ,
    i will use the "CubyHole is a thread " ,but it will make me other problems , i really rather to work here sequentially and not asynchroniaslly way.
    if u have a solution that i don't see , i would really appreciate it if u help me with that ( isn't that the reason why we are here ? ) , since it is not a main issue in my project and i have many other things to do ,like all of us .
    thank you
    and fuck the system

  • Java.io.ObjectInputStream

    Hello,
    I have an applet that reads an object as follows:
    ObjectInputStream result = new ObjectInputStream(in);
    strNameList = (List)result.readObject();
    The .readObject() keeps producing a ClassNotFoundException.
    This error does not occur when i run the applet from within JBuilder, but does when i distribute the applet to a web server.
    Does anyone know why this should occur?
    Thanks,

    Thanks,
    I'm using AWT list - and viewing the applet through IE5 - i also have the java plugin.
    (If i place rt.jar in the archive of the .html file all works fine)
    However if not i keep getting the following error (as a print stack trace):
    java.lang.ClassNotFoundException
         at java/io/ObjectInputStream.loadClass0 (ObjectInputStream.java)
         at java/io/ObjectInputStream.resolveClass (ObjectInputStream.java)
         at java/io/ObjectInputStream.readClassDescriptor (ObjectInputStream.java)
         at java/io/ObjectInputStream.readNewObject (ObjectInputStream.java)
         at java/io/ObjectInputStream.readObject (ObjectInputStream.java)
         at java/io/ObjectInputStream.goToEndOfBlockData (ObjectInputStream.java)
         at java/io/ObjectInputStream.readNewObject (ObjectInputStream.java)
         at java/io/ObjectInputStream.readObject (ObjectInputStream.java)
         at Ticker/Ticker.getData (Ticker.java:205)
         at Ticker/Ticker.init (Ticker.java:159)
         at Ticker/TickerApplet.start (TickerApplet.java:199)
         at com/ms/applet/AppletPanel.securedCall0 (AppletPanel.java)
         at com/ms/applet/AppletPanel.securedCall (AppletPanel.java)
         at com/ms/applet/AppletPanel.processSentEvent (AppletPanel.java)
         at com/ms/applet/AppletPanel.run (AppletPanel.java)
         at java/lang/Thread.run (Thread.java)

  • ObjectInputStream returns a wrong boolean value of a object

    ObjectOutputStream.writeObject once, then change the boolean value of the Contact object, ObjectOutputStream.writeObject again, but when ObjectInputStream.readObject, it returns SAME boolean values which should be different. can somebody explain me this? please. thx
       1. import java.io.*; 
       2. import java.util.*; 
       3.  
       4. public class TestSerializable { 
       5.      
       6.     /** Creates a new instance of TestSerializable */ 
       7.     public static void main(String args[]){ 
       8.         new TestSerializable(); 
       9.     } 
      10.      
      11.     public TestSerializable() { 
      12.         try{ 
      13.             Contact contact = new Contact("email","group",1); // contact.isOnline = true for default; 
      14.              
      15.             FileOutputStream fos = new FileOutputStream("ser"); 
      16.             ObjectOutputStream oos = new ObjectOutputStream(fos); 
      17.  
      18.             oos.writeObject(contact); 
      19.              
      20.             contact.setOnline(false); 
      21.             oos.writeObject(contact); 
      22.  
      23.             oos.flush(); 
      24.  
      25.              
      26.             FileInputStream fis = new FileInputStream("ser"); 
      27.             ObjectInputStream ois = new ObjectInputStream(fis); 
      28.             Contact ccRead1 = (Contact)ois.readObject(); 
      29.             Contact ccRead2 = (Contact)ois.readObject(); 
      30.              
      31.             System.out.println("ccRead1.isOnline() = "+ccRead1.isOnline()); 
    [u]  32.             System.out.println("ccRead2.isOnline() = "+ccRead2.isOnline() + " which should be FALSE. ERROR");  [/u]
      33.                        
      34.             oos.close(); 
      35.             ois.close(); 
      36.              
      37.         } 
      38.         catch(Exception e){ 
      39.             e.printStackTrace(); 
      40.         } 
      41.          
      42.     } 
      43.      
      44. } 
      45.  
      46.  
      47.  
      48.  
      49.  
      50. import javax.swing.tree.DefaultMutableTreeNode; 
      51. import javax.swing.tree.*; 
      52. import java.util.*; 
      53.  
      54. public class Contact extends DefaultMutableTreeNode { 
      55.      
      56.     private String email; 
      57.     private int arrayIndex; 
      58.     private String group; 
      59.     private boolean online; 
      60.      
      61.   
      62.     public Contact(String email,String group,int arrayIndex, boolean online){ 
      63.         this.email = email; 
      64.         this.group = group; 
      65.         this.setArrayIndex(arrayIndex); 
      66.         this.setOnline(online); 
      67.         this.setUserObject(this); 
      68.         this.setAllowsChildren(false);         
      69.     } 
      70.      
      71.     public Contact(String email, String group){ 
      72.         this(email,group,-1,false); 
      73.     } 
      74.      
      75.     public Contact(String email, String group, int arrayIndex){ 
      76.         this(email,group,arrayIndex,true); 
      77.     } 
      78.      
      79.  
      80.      
      81.     public String toString(){ 
      82.         return this.email; 
      83.     } 
      84.  
      85.     public String getEmail() { 
      86.         return email; 
      87.     } 
      88.  
      89.     public int getArrayIndex() { 
      90.         return arrayIndex; 
      91.     } 
      92.  
      93.     public String getGroup() { 
      94.         return group; 
      95.     } 
      96.  
      97.     public boolean isOnline() { 
      98.         return online; 
      99.     } 
    100.  
    101.     public void setOnline(boolean online) { 
    102.         this.online = online; 
    103.     } 
    104.  
    105.     public void setArrayIndex(int arrayIndex) { 
    106.         this.arrayIndex = arrayIndex; 
    107.     } 
    108.  
    109.      
    110. } 

    Did you try the reset() technique again?
    You could also have a look at ObjectOutputStream.writeUnshared().
    And it's not returning a 'wrong value', it is conserving the object graph of the original object sent, which is what it's specified to do and what it's supposed to do. If you don't want that behaviour use reset() or writeUnshared().

Maybe you are looking for

  • Re: Iphoto Not Working After upgrading to Yosemite

    please help i updated my phone to ios 8.1.1 but the voice and data toggle is missing in settings On Wed, Dec 3, 2014 at 12:14 AM, Apple Support Communities Updates <

  • How can I set New Tab Plus as my default tab?

    When I would open a new tab, New Tab Plus would come up, then I could select from my apps that I had added on there. Tonight we had a quick power outage (under 1 minute) while I was out and when I opened Mozilla (that part came up correctly) and clic

  • Digitale Signatur für AddOn-Installer falsch

    Hallo zusammen, ich hab einen AddOn erstellt. Beim istallieren kriege ich eine Meldung: "Digitale Signatur für AddOn-Installer falsch". Woran kann das denn liegen? Gruß Alexnader

  • System calculator and calendar in java!!!

    Hello to everyone! I'm new to Java ! Is it possible to include the system calculator and the system calendar in a Java application??I mean if i push the calendar button, Java opens the system calendar or the same thing with calculator??can anybodu he

  • Passing Files/Folders to BASH script...

    I'm trying to pass a list of files and folders selected in finder to a bash script so that I can use VLC to perform some transcoding and concatenation on them. I'm using "Get Selected Finder Items" to pass the "Files/Folders" output "As Arguments" to