Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 9 of 9

Thread: Error reading objects from file

  1. #1
    Junior Member
    Join Date
    Dec 2013
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Error reading objects from file

    Hi,
    I am trying to put objects in a file and later want to read them.
    I am using following code to add objects in file
    //for adding object in file
    public void addObject() throws IOException, ClassNotFoundException
    {
            ObjectOutputStream objs=new ObjectOutputStream(new FileOutputStream("x:\\ABCD1.dat",true));
            MyClass o1=new MyClass("abc", "abc");
            MyClass o2=new MyClass("cde", "pqr");
            objs.writeObject((Object)o1);
            objs.writeObject((Object)o2);
            objs.flush();
            objs.close();
    }

    And to read object from file i am using following code
    public void getObject() throws FileNotFoundException, IOException
    {
            ObjectInputStream obji=new ObjectInputStream(new FileInputStream("x:\\ABCD1.dat"));
            MyClass my=null;
            boolean flag=true;
            while(flag==true)
            {
                try
                {
                    my=(MyClass)obji.readObject();
                    System.out.println(""+my.str1);
                    System.out.println(""+my.str2);
                }
                catch(Exception e)
                {
                    System.out.println("Now in catch\n"+e);
                    flag=false;
                }
            }
            obji.close();
    }

    This works fine if i add two object on calling a addObject() function.
    But if i modify my addObject() function as shown below
    public void addObject() throws IOException, ClassNotFoundException
     {
            //adding object inside file
            ObjectOutputStream objs=new ObjectOutputStream(new FileOutputStream("x:\\ABCD1.dat",true));
            MyClass o1=new MyClass("abc", "abc");
            objs.writeObject((Object)o1);
            objs.flush();
            objs.close();
    }
    Now when i call this function twice from my main() function it adds two object in file(when i viewed file externally i can see two objects there).
    But when i call getObject() function it reads only one object from file and on trying to read second object it gives following error.
    java.io.StreamCorruptedException: invalid type code: AC
    No matter how many object i insert in a file it reads only first object and then gives above error.
    I am unable to understand what is going wrong in this please help.

    Thanks in advance.


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Error reading objects from file

    Can you post runnable code that demonstrates the error?

  3. #3
    Member andbin's Avatar
    Join Date
    Dec 2013
    Location
    Italy
    Posts
    443
    Thanks
    4
    Thanked 122 Times in 114 Posts

    Default Re: Error reading objects from file

    Quote Originally Posted by prashant.6388 View Post
    ObjectOutputStream objs=new ObjectOutputStream(new FileOutputStream("x:\\ABCD1.dat",true));

    java.io.StreamCorruptedException: invalid type code: AC
    Sorry, there's an important quibble with object serialization: it doesn't work in "append" mode.
    The object serialization uses a well defined byte-level "protocol" and when you create an ObjectOutputStream, the first thing written is a special "header" that marks the stream as specific for serialization.
    If you "append" more times, the file will contain for example:

    [header] [objects......] [header] [objects......]

    When you read and arrive at the second header, the deserialization logic doesn't expect it ..... and fails, supposing that the stream is corrupted.


    Solution: rethink your application, you have to write and read all objects every time.
    Andrea, www.andbin.netSCJP 5 (91%) – SCWCD 5 (94%)

    Useful links for Java beginnersMy new project Java Examples on Google Code

  4. #4
    Junior Member
    Join Date
    Dec 2013
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Error reading objects from file

    Quote Originally Posted by GregBrannon View Post
    Can you post runnable code that demonstrates the error?
    First and second code snippet i have given for inserting and reading object works fine.
    I am using following code to run it.
    public static void main(String args[]) throws IOException, ClassNotFoundException
        {
            FileHandlingObject_Trial1 o1=new FileHandlingObject_Trial1();
            o1.addObject();
            o1.getObject();
        }

    Problem occurs when i modify my addObject() method as shown in second code snippet. getObject() method is same but it reads only one object this time.(in previous case it reads two objects correctly).
    For second time i am using following code to run it.
    public static void main(String args[]) throws IOException, ClassNotFoundException
    {
    FileHandlingObject_Trial1 o1=new FileHandlingObject_Trial1();
    o1.addObject();
    o1.addObject();

    o1.getObject();

    }

  5. #5
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Error reading objects from file

    I believe andbin answered your question.

  6. #6
    Member andbin's Avatar
    Join Date
    Dec 2013
    Location
    Italy
    Posts
    443
    Thanks
    4
    Thanked 122 Times in 114 Posts

    Default Re: Error reading objects from file

    I can add an interesting thing. The main problem is given by that header. It's written or read/verified somewhere by the code into ObjectOutputStream / ObjectInputStream but fortunately this piece of code is well encapsulated in an appropriate method.

    ObjectOutputStream has a protected void writeStreamHeader()
    while
    ObjectInputStream has a protected void readStreamHeader()

    The write/read/check of the header is only here in these methods.
    Since these methods are protected and the classes non-final, technically it's perfectly possible to extend the classes and override these methods just to execute "nothing".

    If you want to choose this solution ... it's absolutely up to you. But beware that the stream will be a "non-standard" stream that, in general, doesn't comply with the object serialization protocol.
    Andrea, www.andbin.netSCJP 5 (91%) – SCWCD 5 (94%)

    Useful links for Java beginnersMy new project Java Examples on Google Code

  7. #7
    Junior Member
    Join Date
    Dec 2013
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Talking Re: Error reading objects from file

    Hey guys thanks for your answers.
    What andbin said is correct each time it adds header before adding object.
    But i figured out that this happens because of following line of code.
    ObjectOutputStream objs=new ObjectOutputStream(new FileOutputStream("x:\\ABCD1.dat",true));

    if i remove this line from addObject() function and place it in void main i can add as many objects as i want.
    It reads object correct with same getObjectFunction().
    I am posting modified code.
    public static void main(String args[]) throws IOException, ClassNotFoundException
        {
            FileHandlingObject_Trial1 o1=new FileHandlingObject_Trial1();
            o1.objs=null;
            [COLOR="#FF0000"]o1.objs=new ObjectOutputStream(new FileOutputStream("x:\\ABCD1.dat",true));[/COLOR]
            o1.addObject();
            o1.addObject();
            o1.getObject();
     
        }
        public void addObject() throws IOException, ClassNotFoundException
        {
            //adding object inside file
    //        objs=new ObjectOutputStream(new FileOutputStream("x:\\ABCD1.dat"));
            MyClass o1=new MyClass("abc", "abc");
            objs.writeObject((Object)o1);
            objs.flush();
    //        objs.close();

    getObject function is same as stated previously.


    Thanks a lot for your help guys.

  8. #8
    Member andbin's Avatar
    Join Date
    Dec 2013
    Location
    Italy
    Posts
    443
    Thanks
    4
    Thanked 122 Times in 114 Posts

    Default Re: Error reading objects from file

    Quote Originally Posted by prashant.6388 View Post
    But i figured out that this happens because of following line of code.
    ObjectOutputStream objs=new ObjectOutputStream(new FileOutputStream("x:\\ABCD1.dat",true));

    if i remove this line from addObject() function and place it in void main i can add as many objects as i want.
    But you have not solved much more .... you are still opening the file in "append" mode. If you run the app 2 times, you corrupt the stream as I have described.
    Andrea, www.andbin.netSCJP 5 (91%) – SCWCD 5 (94%)

    Useful links for Java beginnersMy new project Java Examples on Google Code

  9. #9
    Junior Member
    Join Date
    Dec 2013
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Error reading objects from file

    Quote Originally Posted by andbin View Post
    But you have not solved much more .... you are still opening the file in "append" mode. If you run the app 2 times, you corrupt the stream as I have described.
    I am completely agree with you. Opening file in append more corrupts file.
    I tried it.
    Thanks for your suggestions.

Similar Threads

  1. Reading a file and comparing them to an array to get the file type - java
    By tomb1992 in forum What's Wrong With My Code?
    Replies: 5
    Last Post: March 4th, 2013, 06:13 PM
  2. Error Objects Swing
    By kingdsand in forum AWT / Java Swing
    Replies: 1
    Last Post: July 30th, 2012, 12:23 PM
  3. Replies: 3
    Last Post: December 2nd, 2011, 11:53 AM
  4. Beginner, Reading from file error
    By Lynce in forum File I/O & Other I/O Streams
    Replies: 2
    Last Post: October 27th, 2011, 06:31 AM
  5. problem reading from two files into array objects
    By JavaRTnoob in forum What's Wrong With My Code?
    Replies: 7
    Last Post: May 30th, 2010, 09:21 AM

Tags for this Thread