Object-Streams vs. Serializable

When I send an object (of type DefaultStyledDocument) over the internet using the ObjectOutputStream and ObjectInputStream I get an:
java.io.NotSerializableException: java.lang.Object
but the methods writeObject() and readObject() only takes objects of type Object, which doesn't implement the Serializable-interface...?

It sounds like you are doing something like this:
DefaultStyledDocument doc = new
DefaultStyledDocument;
Object o = doc;
out.writeObject(o);>
Don't pass the object into the writeObject function as
type Object pass the object in as type
DefaultStyledDocument. The class Object is not
serializable and DefaultStyledDocument is.
Do something like this:
out.write(doc);Sorry, but this doesn't matter at all. If you assign an object of class Something to a variable of type Object, the value of the Object variable will still be of type Something.

Similar Messages

  • Retreiving more than one object from an object stream using serialization.

    I have written a number of object into a file using the object Output stream. Each object was added separately with a button event. Now when I retrieve it only one object is being displayed. the others are not displayed The code for retrieval and inserting is given below. Please do help me.
    code for inserting is as follows
    Vehicle veh1 and vehicle class implements serializable
    veh1.vehNum=tf1.getText();
              veh1.vehMake=tf2.getText();
              veh1.vehModel=tf3.getText();
              veh1.driveClass=tf4.getText();
              veh1.vehCapacity=tf5.getText();          
              FileOutputStream out = new FileOutputStream("vehicle.txt",true);
              ObjectOutputStream s = new ObjectOutputStream(out);
              s.writeObject(veh1);
    retrieval
    FileInputStream out = new FileInputStream("vehicle.txt");
              String str1,str2;
              str1=str2=" ";
              Vehicle veh=new Vehicle();
              ObjectInputStream s = new ObjectInputStream(out);
              try
              Vehicle veh1=(Vehicle)s.readObject();
              s.close();
              int i=0;
              str1=veh1.vehNum;
              str2+=str1+"\t";
              str1=veh1.vehMake;
              str2+=str1+"\t";
              str1=veh1.vehModel;
              str2+=str1+"\t";
              str1=veh1.driveClass;
              str2+=str1+"\t";
              str1=veh1.vehCapacity;
              str2+=str1+"\t\n";
              ta1.append(str2);
              catch(Exception e)
              e.printStackTrace();
    Pleas give me the code for moving through the object until it reaches the end of file

    You can read objects from the stream one by one. So, what you need is an endless loop like this:
    // Suppose you have an ObjectInputStream called objIn
    // So here is the loop which reads objects from the stream:
    Object inObj;
    while (1) {
        try {
            inObj=objIn.readObject();
            // Do something with the object we got
            parse_the_object(inObj);
        } catch (EOFException ex) {
            // The EOFException will be thrown when
            // we reached the end of the file, so here we break out
            // of our lovely infinite cycle
            break;
        } catch (Exception ex) {
            ex.printStackTrace();
            // Here you may decide what to do...
            // Probably the processing will end here, too. For now,
            // we moving on, hoping there is still something to read
    objIn.close();
    // ...

  • File I/O Using Object Streams

    My program is supposed to be a Driving instructor program that allows someone to enter a Name and Lesson Number, and it will pull up the Date, and Comments that the lesson took place. The information is saved in a file with the person's name, and saved as an array. We are required to use Object Streams for the file i/o. The only part of the program that I don't have working is the actual file i/o. The large commented section that I have in the datamanager class is the notes from the professor on the board and I haven't removed them yet. There are 4 classes for this file.
    The main class that creates the program and calls the other classes.
    import java.awt.*;
    import javax.swing.*;
    public class main {
    /** Creates a new instance of main */
    public main() {
    * @param args the command line arguments
    public static void main(String[] args)
    guiLayout labelFrame = new guiLayout(); // creates LabelFrame
    labelFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
    labelFrame.setSize(600, 200);
    labelFrame.setVisible(true);
    } The second class is the GUI class and event handler class.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    public class guiLayout extends JFrame{
        private JPanel centertop;
        private JPanel centermiddle;
        private JPanel centerbottom;
        private JLabel dateLabel;
        private JLabel nameLabel;
        private JLabel lessonLabel;
        private JLabel commentsLabel;
        private JTextArea DateTextArea;
        private JTextArea NameTextArea;
        private JTextArea LessonTextArea;
        private JTextArea CommentsTextArea;
        private JButton Save;
        private JButton Retrieve;
        private String tempDay[];
        private DataManager DMO;
        /** Creates a new instance of guiLayout */
        public guiLayout()
            super("Drive Application");
            setLayout(new FlowLayout());
            dateLabel = new JLabel("Date (mm/dd/yy)");
            nameLabel = new JLabel("Name");
            lessonLabel = new JLabel("Lesson (1-10)");
            commentsLabel = new JLabel("Comments");
            DateTextArea = new JTextArea(1, 7);
            NameTextArea = new JTextArea(1, 15);
            LessonTextArea = new JTextArea(1, 2);
            CommentsTextArea = new JTextArea(6, 30);
            Save = new JButton( "Save");
            Retrieve = new JButton( "Retrieve");
            //insert into GUI
            //TOP
            centertop = new JPanel();
            centertop.add(nameLabel);
            centertop.add(NameTextArea);
            centertop.add(lessonLabel);
            centertop.add(LessonTextArea);
            centertop.add(dateLabel);
            centertop.add(DateTextArea);
            centertop.setLayout(new GridLayout(6,1));
            add(centertop, BorderLayout.NORTH);
            centermiddle = new JPanel();
            centermiddle.setLayout(new GridLayout(1,1));
            centermiddle.add(CommentsTextArea);
            add(centermiddle, BorderLayout.CENTER);
            centerbottom = new JPanel();
            centerbottom.setLayout(new GridLayout(1,3));
            centerbottom.add (Save);
            centerbottom.add(Retrieve);
            add(centerbottom, BorderLayout.SOUTH);
            ButtonHandler handler = new ButtonHandler();
            Save.addActionListener( handler);
            Retrieve.addActionListener(handler);
        private class ButtonHandler implements ActionListener
            public void actionPerformed(ActionEvent event)
                String Namein = NameTextArea.getText();
                String Datein = DateTextArea.getText();
                String Commentsin = CommentsTextArea.getText();
                int Lessonin = Integer.parseInt(LessonTextArea.getText());
                if(event.getSource()==Save)
                   DMO.Save(Namein, Datein, Commentsin, Lessonin);
                if(event.getSource()==Retrieve)
                    if(Lessonin >= 1 && Lessonin <= 10)
                       LessonRecord r = (DMO.Retrieve(Namein, Lessonin));
                    else
                        String errormess = "Lesson Number must be between 1 and 10!";
                        CommentsTextArea.setText(errormess);
    }The third class is the DataManager class which handles the actual file i/o.
    import java.io.*;
    import java.util.*;
    public class DataManager implements Serializable
        //private String Path = "P:\\D00766703\\CET431\\Assign5";
        private String Path = "C:\\Java";
        FileInputStream fin;
        FileOutputStream fout;
        ObjectInputStream oin;
        ObjectOutputStream oout;
        public String Retrieve(String name, int lesson)
            String itemFile = Path + name + ".ser";
            File f = new File(itemFile);
            if (f.exists() == true)
                try
                    if(fin == null)
                        fin = new FileInputStream(itemFile);
                        oin = new ObjectInputStream(fin);
                    LessonRecord r[] = oin.readObject();
                    if(fin.available() == 0)
                        oout.close();
                        fout.close();
                        return r[lesson - 1];
                catch(IOException ioe)
                    System.out.print(ioe);
            else
                LessonRecord LR = new LessonRecord();
                LR.date = " ";
                LR.comment = "File Not Found";
                return LR;
        /*create file object for Path\\Name
         *if file exists
         *  create fileinputstream
         *  create objectinputstream - oin
         *  read array of lesson records
         *  LessonRecord |r[] = oin.readObject();    need cast to array here
         *  close object input stream and file input stream
         *  return |r[lesson - 1];
         *else file does NOT EXIST
         *  LessonRecord LR = new LessonRecord();
         *  LR.date = " ";
         *  LR.comment = error message;
         *  return LR;
        public void Save(String name, String date, String comment, int lesson)
            String itemFile = Path + name + ".ser";
            File f = new File(itemFile);
            LessonRecord |r[];
            if (f.exists() == true)
                try
                    fin = new FileInputStream(itemFile);
                    oin = new ObjectInputStream(fin);
                    LessonRecord r[] = oin.readObject();
                catch(IOException ioe)
                    System.out.print(ioe);
            else
                r = new LessonRecord[10];
            r[lesson - 1] = new LessonRecord(date, comment);
            fout = new FileOutputStream(itemFile, true);
            oout = new ObjectOutputStream(fout);
            oout.write(r);
            oout.close();
            fout.close();
        /*create file object for Path\\Name
         *LessonRecord |r[];
         *if file exists
         *  create fileinputstream
         *  create objectinputstream - oin
         *  read array of lesson records
         *  LessonRecord |r[] = oin.readObject();    need cast to array here
         *  close object input stream and file input stream
         *else
         *  |r = new LessonRecord[10];
         *|r[lesson - 1] = new LessonRecord(date, comment);
         *createfileoutputstream(BaseDir\\Name);
         *createobjectoutputstream - oout
         *oout.write(|r);
         *closeobjectstream
         *closefilestream
    }And the fourth class is the LessonRecord class which is serializable and has the date and comments variables.
    import java.io.Serializable;
    public class LessonRecord implements Serializable
        public String Date;
        public String Comment;
        /** Creates a new instance of LessonRecord */
        public LessonRecord()
            Date = "";
            Comment = "";
        public LessonRecord(String Datein, String Commentin)
            Date = Datein;
            Comment = Commentin;
    }I could have sworn that the professor said to make it |r for the account records variable names, but I always get errors when I do that, and I need to know how to cast to an array too.

    hi Friend,
    I have made some modification to your code. and try this...I think it will help you...
    /*guiLayout.java*/
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    public class guiLayout extends JFrame{
        private JPanel centertop;
        private JPanel centermiddle;
        private JPanel centerbottom;
        private JLabel dateLabel;
        private JLabel nameLabel;
        private JLabel lessonLabel;
        private JLabel commentsLabel;
        private JTextArea DateTextArea;
        private JTextArea NameTextArea;
        private JTextArea LessonTextArea;
        private JTextArea CommentsTextArea;
        private JButton Save;
        private JButton Retrieve;
        private String tempDay[];
        private DataManager DMO;
        /** Creates a new instance of guiLayout */
        public guiLayout()
            super("Drive Application");
            DMO=new DataManager();
            setLayout(new FlowLayout());
            dateLabel = new JLabel("Date (mm/dd/yy)");
            nameLabel = new JLabel("Name");
            lessonLabel = new JLabel("Lesson (1-10)");
            commentsLabel = new JLabel("Comments");
            DateTextArea = new JTextArea(1, 7);
            NameTextArea = new JTextArea(1, 15);
            LessonTextArea = new JTextArea(1, 2);
            CommentsTextArea = new JTextArea(6, 30);
            Save = new JButton( "Save");
            Retrieve = new JButton( "Retrieve");
            //insert into GUI
            //TOP
            centertop = new JPanel();
            centertop.add(nameLabel);
            centertop.add(NameTextArea);
            centertop.add(lessonLabel);
            centertop.add(LessonTextArea);
            centertop.add(dateLabel);
            centertop.add(DateTextArea);
            centertop.setLayout(new GridLayout(6,1));
            add(centertop, BorderLayout.NORTH);
            centermiddle = new JPanel();
            centermiddle.setLayout(new GridLayout(1,1));
            centermiddle.add(CommentsTextArea);
            add(centermiddle, BorderLayout.CENTER);
            centerbottom = new JPanel();
            centerbottom.setLayout(new GridLayout(1,3));
            centerbottom.add (Save);
            centerbottom.add(Retrieve);
            add(centerbottom, BorderLayout.SOUTH);
            ButtonHandler handler = new ButtonHandler();
            Save.addActionListener( handler);
            Retrieve.addActionListener(handler);
        private class ButtonHandler implements ActionListener
            public void actionPerformed(ActionEvent event)
                String Namein = NameTextArea.getText();
                int Lessonin = Integer.parseInt(LessonTextArea.getText());
                if(event.getSource()==Save)
                    String Datein = DateTextArea.getText();
                     String Commentsin = CommentsTextArea.getText();
                   DMO.Save(Namein, Datein, Commentsin, Lessonin);
                if(event.getSource()==Retrieve)
                    if(Lessonin >= 1 && Lessonin <= 10)
                       LessonRecord r = (DMO.Retrieve(Namein, Lessonin));
                       System.out.println("Retrieve:"+ r.Comment+":"+r.Date);
                    else
                        String errormess = "Lesson Number must be between 1 and 10!";
                        CommentsTextArea.setText(errormess);
    /*DataManager.java*/
    import java.io.*;
    import java.util.*;
    public class DataManager implements Serializable
        //private String Path = "P:\\D00766703\\CET431\\Assign5";
        private String Path = "C:/Java";
        FileInputStream fin;
        FileOutputStream fout;
        ObjectInputStream oin;
        ObjectOutputStream oout;
        public LessonRecord Retrieve(String name, int lesson)
            String itemFile = Path + name + ".ser";
            File f = new File(itemFile);
            LessonRecord[] r=null;
            if (f.exists() == true)
                try
                    if(fin == null)
                        fin = new FileInputStream(itemFile);
                        oin = new ObjectInputStream(fin);
                    r= (LessonRecord[])oin.readObject();
                    System.out.println(r[lesson-1].Comment+":"+r[lesson-1].Date);
                catch(IOException ioe)
                    System.out.print(ioe);
                  catch(ClassNotFoundException c){
                    c.printStackTrace();
                finally
                    try {
                        if(fin!=null)fin.close();
                        if(oin!=null)oin.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
            else
                LessonRecord LR = new LessonRecord();
                LR.Date = " ";
                LR.Comment = "File Not Found";
                return LR;
        /*create file object for Path\\Name
         *if file exists
         *  create fileinputstream
         *  create objectinputstream - oin
         *  read array of lesson records
         *  LessonRecord |r[] = oin.readObject();    need cast to array here
         *  close object input stream and file input stream
         *  return |r[lesson - 1];
         *else file does NOT EXIST
         *  LessonRecord LR = new LessonRecord();
         *  LR.date = " ";
         *  LR.comment = error message;
         *  return LR;
      return r[lesson - 1];
        public void Save(String name, String date, String comment, int lesson)
            String itemFile = Path + name + ".ser";
            File f = new File(itemFile);
            LessonRecord r[]=new LessonRecord[10];
            if (f.exists() == true)
                try
                    fin = new FileInputStream(itemFile);
                    oin = new ObjectInputStream(fin);
                     r = (LessonRecord[])oin.readObject();
                catch(IOException ioe)
                    System.out.print(ioe);
                catch(ClassNotFoundException c){
                    c.printStackTrace();
                finally
                    try {
                        if(fin!=null)fin.close();
                        if(oin!=null)oin.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
            else
                r = new LessonRecord[10];
       try
            r[lesson - 1] = new LessonRecord(date, comment);
            fout = new FileOutputStream(itemFile);
            oout = new ObjectOutputStream(fout);
            oout.writeObject(r);
            oout.flush();
       catch(IOException ioe)
            finally
                try {
                    if(fout!=null)fout.close();
                    if(oout!=null)oout.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
        /*create file object for Path\\Name
         *LessonRecord |r[];
         *if file exists
         *  create fileinputstream
         *  create objectinputstream - oin
         *  read array of lesson records
         *  LessonRecord |r[] = oin.readObject();    need cast to array here
         *  close object input stream and file input stream
         *else
         *  |r = new LessonRecord[10];
         *|r[lesson - 1] = new LessonRecord(date, comment);
         *createfileoutputstream(BaseDir\\Name);
         *createobjectoutputstream - oout
         *oout.write(|r);
         *closeobjectstream
         *closefilestream
    }main.java and LessonRecord.java does not have any changes so you use the old code....
    Thanks
    Edited by: rajaram on Sep 28, 2007 1:24 PM

  • "Hacking" the Object streams...

    Hello everyone,
    Here's what I'm trying to do:
    I have to transmit Object graphs over a message oriented networking framework at a rate of about 100 messages per second. Since i can't maintain constant data streams between the peers the first thing that comes in mind is to create an ObjectOutputStream to "fill in" each message and on the far side an ObjectInputStream to read the contents of each message. This aproach however seems to be too coastly for the goals I have to meet. So the first questin I have is:
    How coastly realy it is to create 200 Object streams per second?
    And the second question I got is:
    Is there a way to safely reuse only a single pair of Object streams?
    I tried to run the object streams over my custom implenentations of OutputStream and InputStream that allow me to write the object, flush the object stream, obtain the byte[] block that was produced, fill it in a message and transmit it. On the far side I respectively "slip" this byte[] block "beneath" the ObjectInputStream and reconstruct the Object. This aproach worked for simple data structures and yelded the desired high throughput. With complex structured however this yelds horrific StreamCorruptedExceptions :(

    I think creating 200 streams per second can't be fast. But a stream can send as much data as you want to push thru it (underlying connection mechanism restrictions apply... e.g. TCP over the internet is not as fast as TCP over a LAN or within the same PC).
    If you're large objects are not containing all serializable contents, that could cause problems, I think. Sticking a non-serializable object inside a serializable one doesn't make the non-serializable one serializable.

  • Object Stream Bug?

    I use ObjectInputStream and ObjectOutputStream to pass a Serializable class. All of the classes members are serializable, but before it's sent, its members are the appropriate value. Then on the recieving end its members are the value when the class was instantiated. When I say before and after I mean right before and right after. Just the object gets serialized and sent and deserialized and its members change value. Is this common for Object streams?

    has the object been sent using that ObjectOutputStream before? a pair of object streams keep handles to all the objects that have been passed between them. so if you send an object a second time it doesn't actually send the object again, it just sends the handle. this is to allow the streams to deal with graphs of objects and circular references. a side effect of this is that if you send an object, change some of its fields and then send it again then at the other end of the stream the object will appear as it did the first time it was sent. if you call reset() on the ObjectOutputStream then it discards all the handles and sending an object again will result in a new copy being sent and any changes will be visible at the other end of the stream. another potentially serious side effect of this is that objects that have been sent down the stream never become available for garbage collection as the streams retain references to them. calling reset() also solves this problem. have a look at the serialization FAQ:
    http://java.sun.com/products/jdk/serialization/faq/

  • Object stream problems

    Hi guys
    i'm trying to write a small client / server application where the server will send an sql query to a jdbc database and then send the results to the client.
    So far i have set up the database and have got the server to succesfully send the query and store the result in a ResultSet object. The problem i have now is sending this object through a stream to the client.
    To do this i have a class called ResultOBJ that implements the serializable interface and has a result set object inside, the server sets this to the ResultSet that contains the results of the query. It then sends this to the client using the ObjectOutputStream and is read using the ObjectInputStream.
    However whenever i try this the server produces a NotSerializableException and i can't figure out what is going wrong.
    This is the part of the code that sends the object .....
    out = new ObjectOutputStream(skt.getOutputStream());
    resu = new ResultOBJ(out);
    Class.forName(driverName);
    conn = DriverManager.getConnection(dbURL, username, password);
    Statement stmt = conn.createStatement();
    String SQLcmd = "SELECT * FROM BOOKS";
    resu.setResultSet(stmt.executeQuery(SQLcmd));
    out.writeObject(resu);
    out.flush();
    System.out.println("Results sent");
    out.close();
    skt.close();
    To read in the object i use ......
    inst = new ObjectInputStream(in.getInputStream());
    rs = (ResultOBJ) inst.readObject();
    where rs is a ResultOBJ class.
    Finally the ResultOBJ class is defined as follows ....
    public class ResultOBJ implements Serializable
    private ResultSet rs;
    private ObjectOutputStream outst;
    public ResultSet getResultSet(){
    return rs;
    public void setResultSet(ResultSet in){
    rs = in;
    public void next() throws SQLException{
    rs.next();
    public String getString(int columnIndex) throws SQLException{
    return rs.getString(columnIndex);
    public ResultOBJ(ObjectOutputStream oos)
    outst = oos;
    I've spent about a week on this single problem and haven't been able to solve it, i know everything should work because if i change the line that send the object i.e.
    out.writeObject(resu);
    to
    out.writeObject("Some Text");
    and then print the result after reading it in it all works, so i know the connection works, i know the jdbc query was successful.
    I'd REALLY appreciate any help you can give me with this because it's driving me mad

    pogotc,
    ResultSets objects are not serializable, so you cannot send directly a ResultSet object trough a stream. To send your query results over serialization, you must read and store each returned record in a specific object that represents data stored in your table BOOK, and add this object to a list, like ArrayList.

  • Lost Object[] data after serialization

    Hi all,
    I posted this problem already in the servlet forum, but now I found out that it's more a serialization problem. I hope you guys can help me!!!!
    I have a problem sending a serialized object from a java application to a servlet (inside Tomcat).
    I'm using Commons HttpClient's PostMethod to get a connection to the servlet over https. The encryption should be done automatically within HttpClient and Tomcat.
    The object container I'm sending contains a few Strings and an Object[] that is filled with Strings.
    The container i'm sending implements Serializable.
    The connection is working fine, and the object has no serialization problems but the incoming request at server-side is kind of broken.... The single Strings are the same I've set on client-side, but the Object[] is null. I tried it with directly sending the ArrayList but with the same result.
    The size of the incoming data stream is the same as it was on client side.
    The funny thing is that sending data back from server to client works perfectly fine. My Object[] goes through without any problems!
    Here is the client code I'm using:
    PostMethod method = new PostMethod(mServerUrl);
    MyContainer container = new MyContainer("Message2Server",new Object[]{"ArrayElement1"});
    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    ObjectOutputStream serializer = new ObjectOutputStream(byteStream);
    serializer.writeObject(container);
    serializer.flush( );
    serializer.close();
    method.setRequestHeader("Content-Type","binary/x-java-serialized");
    ByteArrayRequestEntity output = new ByteArrayRequestEntity(byteStream.toByteArray());
    method.setRequestEntity(output);
    mClient.executeMethod(method);...and here is the servlet code:
    InputStream is = request.getInputStream();
    ObjectInputStream ois = new ObjectInputStream(is);
    MyContainer out = (MyContainer) ois.readObject();
    out.getString1(); //<-- is OK!
    out.getString2(); //<-- is OK!
    out.getObjectArray(); //<-- is null!!!!!!
    out.setObjectArray(new Object[]{"Message for the Client!!!"});
    response.setContentType("binary/x-java-serialized");
    // get output stream and send it back
    OutputStream os = response.getOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(os);
    oos.writeObject(out);
    oos.flush();
    oos.close();Does anybody see a solution????
    I think it just could be two things:
    - Serialization fails for any reason?!
    - The Servlet InputStream fails?
    Thanx for any help!
    CU Jan

    This looks very useful to me. Can you tell us what
    the typo was?Considering he/she hasn't posted for 4 months, I'd doubt it.

  • How to Edit/Save PDF without Object Stream Compression?

    Hi,
    Whenever I am removing/replacing a page in the PDF file, "Object Stream Compression" applied automatically. But in the original PDF there is no "Object Stream Compression" initially.
    I can remove this "Object Stream Compression" using the option "PDF OPTIMIZER->Cleanup->Remove->Compression" manually, but I want to remove/replace a page in the PDF file without "Page Has Object Stream Compression".
    Preflight Report for the Original PDF
    Preflight Report for the Edited PDF (One Page Removed)
    Could you advise anyone, how to solve the above mentioned issue?
    I hope your favorable response from the Acrobat experts.
    Regards,
    TSR

    Thanks for the reply.
    I just want to remind you that I don't use any other workflow to retain/remove the "object stream compression".
    My question is "object stream compression" was not present in the original PDF  but after removing a page (Ex: Back cover) "object stream compression" applied automatically. Why?
    Note: I am using "Acrobat X pro" to remove a page (Ex: Back cover) from the original PDF and not using any other PDF tools for the above.
    Now i hope that you will understand the actual issue.
    Regards,
    Raja. S

  • Testing Object Equality using Serialization

    Hey everyone! I was wondering if somebody could help me figure out how to compare two objects using serialization.
    I have two objects that I'm trying to compare. Both of these objects extend a common "Model" class that has a method getSerialized() that returns a serialized form of an instance, shown below:
              // Serialize the object to an array
             ByteArrayOutputStream baos = new ByteArrayOutputStream(1000);
             ObjectOutputStream oos;
              try {
                   oos = new ObjectOutputStream(baos);
                  oos.writeObject(this);
                  oos.close();
              } catch (IOException e) {
                   e.printStackTrace();
             //Deserialize array into a String array
             return baos.toByteArray();This Model class also has an equals(Model obj) method that allows for the current model object to be compared to a model object that is passed in:
            //Store both models' serialized forms into byte arrays
            byte [] thisClass = this.getSerialized();
            byte [] otherClass = obj.getSerialized();This is where things get a little funny. The byte arrays don't equal - one array is a byte larger than the other. If a byte-by-byte comparison is done, the arrays are equal for the first 15-20% and then not equal for the rest. If I deserialize the byte arrays back into Models and do a toString() on those models, I find that they are equal.
    I have a feeling there's something about the serialization process that I don't fully comprehend. Is there a way to properly implement object comparison using serialization?
    Thanks in advance!

    When you serialize an object, you also serialize the entire tree of references based on that object (except for transient variables). That tree is the complicated business you described there. Serialization stores all the objects in the tree, along with data that explains which objects refer to which other objects. Furthermore if the tree is actually a graph, and there are multiple ways to get to an object, it still only stores each object once. I don't see any reason to believe that all that relationship data would be encoded identically for a pair of trees that you deemed to be equal. And your experiment shows that indeed it isn't.

  • All session objects should be serializable to replicate error.

    Hi All,
    Having 'EmployeeBean' and it is having below properties with getters and setters methods
    private long emp_id;
    private String emp_name;
    private java.sql.Timestamp date_of_join;
    private boolean isActive;
    private int dept_no;
    Adding multiple employees(creating multiple EmployeeBean) into an ArrayList and storing this ArrayList into a Session object. This is working fine but when I move this code to production(cluster environment) it is throwing below error
    <Aug 23, 2011 2:15:40 PM EDT> <Error> <Cluster> <BEA-000126> <All session objects should be serializable to replicate. Check the objects in your session. Failed to replicate non-serializable object.
    java.rmi.MarshalException: failed to marshal update(Lweblogic.cluster.replication.ROID;ILjava.io.Serializable;Ljava.lang.Object;); nested exception is:
         java.io.NotSerializableException: my.company.beans.EmployeeBean
         at weblogic.rjvm.BasicOutboundRequest.marshalArgs(BasicOutboundRequest.java:90)
         at weblogic.rmi.internal.BasicRemoteRef.invoke(BasicRemoteRef.java:221)
         at weblogic.cluster.replication.ReplicationManager_1032_WLStub.update(Unknown Source)
         at sun.reflect.GeneratedMethodAccessor163.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         Truncated. see log file for complete stacktrace
    Caused By: java.io.NotSerializableException: my.company.beans.EmployeeBean
         at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1156)
         at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:326)
         at java.util.ArrayList.writeObject(ArrayList.java:570)
         at sun.reflect.GeneratedMethodAccessor21.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         Truncated. see log file for complete stacktrace
    Can someone please let me know, why I'm getting this error? The EmployeeBean should implement serializable? Is there any problems/cons to implement serializable?
    Having other bean(LoginBean) and I'm keeping this bean into session and it doesn't implement serializable, not getting any error for this bean(LoginBean). Only difference is LoginBean is not added to ArrayList.
    Why it is throwing error for EmployeeBean and not for LoginBean??
    Thanks in advance.
    Regards,
    Sharath.

    The EmployeeBean should implement serializable? - Yep Is there any problems/cons to implement serializable? - No
    Just add java.io.Serializable to the EmployeeBean, for example,
    public class EmployeeBean implements Serializable {
    }For LoginBean you have probably, configured to be in the session, by using faces-config.xml.
    In the case of EmployeeBean (or the object graph it is part of) have you used HttpSession.setAttribute(...)?
    Note that setAtttibute(...) is the trigger for an application server to replicate the object.
    In this case all objects in the object graph have to be serializable.
    Typically, objects should be Serializable when they are part of the session and you are using a clustered environment.

  • How to compress non-image object streams using maximum compression in acrobat x pro

    How to compress non-image object streams using maximum compression in acrobat x pro
    Please provide the screenshot if possible. Thanks!

    ZIP is the best compression for non-image streams, and it will almost certainly already have been used.

  • System code 1, error 43. English text was "Expected an object Stream"

    All,
    I have been working on the same form for several weeks (In Livecycle 8.0). Today when I went to open it, I get the error message "Library returned system code 1, error 43. English text was "Expected an object Stream" " and the only option I have is to say okay, and the windows closes.
    Background:
    The Original Form was a MS Word Document that I converted to a pdf, and use Livecycle 8.0 to add drop down menus, fields etc. to it.
    We have been using the form in reader for days, (testing it) and it still works fine in adobe reader, we can still open it without any problems.
    However I needed to add more options to my drop down menu's and when I attempt to open the pdf file in Livecycle, all of sudden I get this error, system code 1, error 43.
    I have googled, it a didnt find any help, and I have looked / searched the knowledge base with no luck.
    Thank you for any assistance!
    duffie

    I have not seen that error ...can you email it to [email protected] and I will have a look

  • Random access file with object stream

    Hi All,
    I have saved some objects in a file using object stream. While reading the sequential read is possible for me. I want to reduce the overhead of reading whole file for getting one specific object details. Is there any way in which we can implement RandomAccessFile with object stream? or is there any other alternative of reaching specific object in the file without seqential read?

    is there any
    other alternative of reaching specific object in the
    file without seqential read?Write the objects to a database.

  • Socket + GZip Stream + Object Stream problem

    Hello,
    I've been having a problem with my threaded networked application. I want to send GZipped Objects over a socket, but the ObjectInputStream constructor blocks. I understand that it is waiting for header information from the corresponding ObjectOutputStream. I am sure that the socket connection has been established, and the ObjectOutputStream is constructed before the ObjectInputStream on the other end. The header information never seems to get to the other end.
    If I remove the Gzip filter stream, everything works great. I'm thinking that the Gzip stream is buffering the 4 bytes of header info, waiting for more data before actually compressing anything. I've tried flushing everything, to no help. I've tried finish()ing the Gzip stream, but that means I can't send my object payload. I've checked the buffers of all the stream objects and see the Object Stream's header in its buffer, but never seems to get into the GZIPOutputStream's buffer.
    Has anyone successfully used Object Stream > GZIP Stream > Socket Stream before?
    I'm not interested in examples that use file streams, since I get the impression that Gzip works fine with those (and maybe even designed only for those, not for sockets).
    Thanks for any help.
    Dave C

    Thanks. I see what I'm doing differently now. I was trying to send multiple objects over the gzip stream, not 1 at a time, finish(), and construct a new Gzip and Object output stream.
    Seems to work with a ByteArrayOutput/InputStream, now to try with a socket..

  • Root object in Object Stream in Encrypted file

    I cannot find anywhere in the PDF Spec a prohibition on including the Root object in an Object Stream in a non-linearized encrypted file, but Acrobat products appear to assume such a restriction.
    Encrypted files where the Root obj is in an Object Stream do not open with Acrobat 7, 8 or Reader 9, but do open with GhostView/Ghostscript, Foxit, and Adobe Digital Editions.
    If the file is not encrypted there is no problem with the Root object appearing in an Object Stream, and if the Root object is a 'normal' encrypted object there is also no problem.
    Anyone any ideas?
    Matthew Fitzgerald

    Hey praveen,
    If you dont use ehp1, there is no any transaction to create root object. you can fallow this [wiki|http://wiki.sdn.sap.com/wiki/display/CRM/CreateaZBOLObjectPart1] page.
    Regards,
    Zafer,

Maybe you are looking for

  • Intermittent lock ups

    Any ideas as to why my computer locks up or freezes for a 10 seconds then it starts going again? What kind of clues should I be looking at?

  • Java not showing up in Applications folder

    Why is Java not showing up in my Applications folder, even though it's installed and working?  I've done a search for it on the computer and nothing shows up, yet it's functioning.

  • How to update Flash Builder 4 beta 2 so that it remains compatible with snapshots?

    I have Flash Builder 4 beta 2 STANDALONE installed on my Mac (MacOSX 10.6) and I just upgraded my Flex SDK to the latest stable snapshot (4.0.0.13875). Now it seems that the visual designer is not very happy with this upgrade. And in "Using Gumbo bui

  • How to copy Base Document Series to Target Documet

    Hi Experts, i have a multiple series of document when i select one of them in PO and then copy this  PO to A/P Invoice then this series is not get copied to A/p Invoice, so how to copy this series to target document please help me find the attachment

  • Link between CHMs

    I want to create a link between two CHMs that reside in the same directory from the TOC. For example, just for context, I have the following: Link 1 Link 2 Link 3 Link 3 links to a remote topic. The link opens successfully in the right pane of the CH