Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / October 2005

Tip: Looking for answers? Try searching our database.

Problem appending Objects to File

Thread view: 
Marcelo - 25 Oct 2005 10:41 GMT
Dear programmers.

I am having a hard, very hard time trying to add objects to an existing
.dat file.

For exemple, i have an object in the file "file.dat", and I want to add
another object, so I give to the constructor the "true" parameter.

try{
    //TODO: A problem for appending elements
    FileOutputStream fos = new FileOutputStream("file.dat", true);
    ObjectOutputStream oos = new ObjectOutputStream(fos);
           
    oos.writeObject(userObj);
    oos.close();       
}....

However, when I try to add another object with this code, there is a
IOException that i don't really understand.

can you help me?

thanks

Marcelo
Marcelo - 25 Oct 2005 10:43 GMT
The IOException is when I read the Object file;

java.io.StreamCorruptedException
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1326)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:339)
    at fileTools.FileTools.getUserDefListFromFile(FileTools.java:303)
    at plotImages.SimChooser.initLists(SimChooser.java:99)

why???

thanks,

Marcelo
Sharp Tool - 25 Oct 2005 12:42 GMT
> The IOException is when I read the Object file;
>
[quoted text clipped - 9 lines]
>
> Marcelo

It maybe that the appending object and the object your appending to needs to
implement the serializable interface.

Sharp Tool
Roedy Green - 25 Oct 2005 12:45 GMT
>java.io.StreamCorruptedException
>    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1326)
>    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:339)
>    at fileTools.FileTools.getUserDefListFromFile(FileTools.java:303)
>    at plotImages.SimChooser.initLists(SimChooser.java:99)

See http://mindprod.com/jgloss/gotchas.html#SERIALIZATION
and
http://mindprod.com/jgloss/runerrormessages.html#STREAMCORRUPTEDEXCEPTION

I wrote myself a little SSCCE to investigate appending.  I generated
it with the file I/O Amanuensis to help avoid clerical errors.

See http://mindprod.com/applets/fileio.html

// test ability to append to a serialized object stream
import java.io.*;

public class ObjAppend
  {

  /**
   * write some string objects to serialized file
   */
  private static void write1() throws IOException
  {
     // O P E N
     FileOutputStream fos = new FileOutputStream( "C:/temp/temp.ser",
false /* append */ );
     BufferedOutputStream bos = new BufferedOutputStream( fos, 4096
/* buffsize */ );
     ObjectOutputStream oos = new ObjectOutputStream( bos );

     // W R I T E
     oos.writeObject( "a string" );
     oos.writeObject( "a second string" );
     oos.reset();
     oos.writeObject( "a third string" );

     oos.flush();

     // C L O S E
     oos.close();
  }

  /**
   * Append a string object to serialized file
   */
  private static void write2() throws IOException
  {
     // O P E N
     FileOutputStream fos = new FileOutputStream( "C:/temp/temp.ser",
true /* append */ );
     BufferedOutputStream bos = new BufferedOutputStream( fos, 4096
/* buffsize */ );
     ObjectOutputStream oos = new ObjectOutputStream( bos );

     // W R I T E

     oos.writeObject( "a fourth string, appended" );
     oos.flush();

     // C L O S E
     oos.close();
  }

  /**
   * read back four strings from serialized file
   */
  private static void read1() throws IOException,
ClassNotFoundException
  {
     // O P E N
     FileInputStream fis = new FileInputStream( "C:/temp/temp.ser" );
     BufferedInputStream bis = new BufferedInputStream( fis, 4096 /*
buffsize */ );
     ObjectInputStream ois = new ObjectInputStream( bis );

     // R E A D   four strings
     for ( int i=0; i<4; i++ )
        {
        System.out.println( (String) ois.readObject() );
        }

     // C L O S E
     ois.close();
  }
  /**
   * test ability to append to a serialiszed object stream
   *
   * @param args not used
   */
  public static void main ( String[] args )
     {
     try
        {
        write1();
        write2();
        read1();
        }
     catch ( Exception e )
        {
        e.printStackTrace();
        }

     }  // end main
  }
---------------------------------

It dies with the following, output just like yours reading the
appended string.

a string
a second string
a third string
java.io.StreamCorruptedException
       at java.io.ObjectInputStream.readObject0(Unknown Source)
       at java.io.ObjectInputStream.readObject(Unknown Source)
       at ObjAppend.read1(ObjAppend.java:63)
       at ObjAppend.main(ObjAppend.java:80)

The key to why this fails can be found by examining the file
c:\temp\temp.ser with a hex viewer.  See
http://mindprod.com/jgloss/hex.html

In short, what gets written to the file on an append is not the same
as when you do a reset.  readObject is not smart enough to ignore
extra stream init stuff in the middle of a stream.

So the short answer is, you can't append. You must write to a new
file, or copy and write to a new file.

Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Again taking new Java programming contracts.

Roedy Green - 25 Oct 2005 12:02 GMT
>However, when I try to add another object with this code, there is a
>IOException that i don't really understand.

What does the IOException/stack trace say? What does your code say the
stack trace is pointing to?
Signature

Canadian Mind Products, Roedy Green.
http://mindprod.com Again taking new Java programming contracts.

Gordon Beaton - 25 Oct 2005 13:55 GMT
> I am having a hard, very hard time trying to add objects to an
> existing .dat file.
[quoted text clipped - 13 lines]
> However, when I try to add another object with this code, there is a
> IOException that i don't really understand.

If you created the file with separate ObjectOutputStreams (one to
create the additional file, and one or more additional
ObjectOutputStreams to append to it) then you need to use multiple
ObjectInputStreams to read back the file contents in exactly the same
manner, which probably isn't practical at all.

You should try to create the file with *one* ObjectOutputStream, then
read it back with one ObjectInputStream (or use separate files, one
per ObjectOutputStream/ObjectInputStream).

/gordon

Signature

[  do not email me copies of your followups  ]
g o r d o n + n e w s @  b a l d e r 1 3 . s e



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.