ObjectInput Stream & objectOutputStream

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • khajeddin
    New Member
    • Nov 2006
    • 51

    ObjectInput Stream & objectOutputStream

    hi:
    i have a program which should read and werite on a file but after the first time it writeon the file it can read te records.but other times it write on the file but just read the records which has written first time. here is my programs:
    [CODE=java]

    import java.io.FileOut putStream;
    import java.io.IOExcep tion;
    import java.io.ObjectO utputStream;
    import java.util.NoSuc hElementExcepti on;
    import java.util.Scann er;

    import com.deitel.jhtp 7.ch14.AccountR ecordSerializab le;

    public class CreateSequentia lFile
    {
    private ObjectOutputStr eam output; // outputs data to file

    // allow user to specify file name
    public void openFile()
    {
    try // open file
    {
    output = new ObjectOutputStr eam(
    new FileOutputStrea m( "clients.se r" ,true) );
    } // end try
    catch ( IOException ioException )
    {
    System.err.prin tln( "Error opening file." );
    } // end catch
    } // end method openFile

    // add records to file
    public void addRecords()
    {
    AccountRecordSe rializable record; // object to be written to file
    int accountNumber = 0; // account number for record object
    String firstName; // first name for record object
    String lastName; // last name for record object
    double balance; // balance for record object

    Scanner input = new Scanner( System.in );

    System.out.prin tf( "%s\n%s\n%s\n%s \n\n",
    "To terminate input, type the end-of-file indicator ",
    "when you are prompted to enter input.",
    "On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
    "On Windows type <ctrl> z then press Enter" );

    System.out.prin tf( "%s\n%s",
    "Enter account number (> 0), first name, last name and balance.",
    "? " );

    while ( input.hasNext() ) // loop until end-of-file indicator
    {
    try // output values to file
    {
    accountNumber = input.nextInt() ; // read account number
    firstName = input.next(); // read first name
    lastName = input.next(); // read last name
    balance = input.nextDoubl e(); // read balance

    if ( accountNumber > 0 )
    {
    // create new record
    record = new AccountRecordSe rializable( accountNumber,
    firstName, lastName, balance );
    output.writeObj ect( record ); // output record
    } // end if
    else
    {
    System.out.prin tln(
    "Account number must be greater than 0." );
    } // end else
    } // end try
    catch ( IOException ioException )
    {
    System.err.prin tln( "Error writing to file." );
    return;
    } // end catch
    catch ( NoSuchElementEx ception elementExceptio n )
    {
    System.err.prin tln( "Invalid input. Please try again." );
    input.nextLine( ); // discard input so user can try again
    } // end catch

    System.out.prin tf( "%s %s\n%s", "Enter account number (>0),",
    "first name, last name and balance.", "? " );
    } // end while
    } // end method addRecords

    // close file and terminate application
    public void closeFile()
    {
    try // close file
    {
    if ( output != null )
    output.close();
    } // end try
    catch ( IOException ioException )
    {
    System.err.prin tln( "Error closing file." );
    System.exit( 1 );
    } // end catch
    } // end method closeFile
    } // end class CreateSequentia lFile

    [/CODE]
    [CODE=java]

    import java.io.EOFExce ption;
    import java.io.FileInp utStream;
    import java.io.IOExcep tion;
    import java.io.ObjectI nputStream;

    import com.deitel.jhtp 7.ch14.AccountR ecordSerializab le;

    public class ReadSequentialF ile
    {
    private ObjectInputStre am input;

    // enable user to select file to open
    public void openFile()
    {
    try // open file
    {
    input = new ObjectInputStre am(
    new FileInputStream ( "clients.se r" ) );
    } // end try
    catch ( IOException ioException )
    {
    System.err.prin tln( "Error opening file." );
    } // end catch
    } // end method openFile

    // read record from file
    public void readRecords()
    {
    AccountRecordSe rializable record;
    System.out.prin tf( "%-10s%-12s%-12s%10s\n", "Account",
    "First Name", "Last Name", "Balance" );

    try // input the values from the file
    {
    while ( true )
    {
    record = ( AccountRecordSe rializable ) input.readObjec t();

    // display record contents
    System.out.prin tf( "%-10d%-12s%-12s%10.2f\n",
    record.getAccou nt(), record.getFirst Name(),
    record.getLastN ame(), record.getBalan ce() );
    } // end while
    } // end try
    catch ( EOFException endOfFileExcept ion )
    {
    return; // end of file was reached
    } // end catch
    catch ( ClassNotFoundEx ception classNotFoundEx ception )
    {
    System.err.prin tln( "Unable to create object." );
    } // end catch
    catch ( IOException ioException )
    {
    System.err.prin tln( "Error during reading from file." );
    } // end catch
    } // end method readRecords

    // close file and terminate application
    public void closeFile()
    {
    try // close file and exit
    {
    if ( input != null )
    input.close();
    System.exit( 0 );
    } // end try
    catch ( IOException ioException )
    {
    System.err.prin tln( "Error closing file." );
    System.exit( 1 );
    } // end catch
    } // end method closeFile
    } // end class ReadSequentialF ile

    [/CODE]
    what should i do to always read all records ?
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    Originally posted by khajeddin
    hi:
    i have a program which should read and werite on a file but after the first time it writeon the file it can read te records.but other times it write on the file but just read the records which has written first time. here is my programs:
    [CODE=java]

    import java.io.FileOut putStream;
    import java.io.IOExcep tion;
    import java.io.ObjectO utputStream;
    import java.util.NoSuc hElementExcepti on;
    import java.util.Scann er;

    import com.deitel.jhtp 7.ch14.AccountR ecordSerializab le;

    public class CreateSequentia lFile
    {
    private ObjectOutputStr eam output; // outputs data to file

    // allow user to specify file name
    public void openFile()
    {
    try // open file
    {
    output = new ObjectOutputStr eam(
    new FileOutputStrea m( "clients.se r" ,true) );
    } // end try
    catch ( IOException ioException )
    {
    System.err.prin tln( "Error opening file." );
    } // end catch
    } // end method openFile

    // add records to file
    public void addRecords()
    {
    AccountRecordSe rializable record; // object to be written to file
    int accountNumber = 0; // account number for record object
    String firstName; // first name for record object
    String lastName; // last name for record object
    double balance; // balance for record object

    Scanner input = new Scanner( System.in );

    System.out.prin tf( "%s\n%s\n%s\n%s \n\n",
    "To terminate input, type the end-of-file indicator ",
    "when you are prompted to enter input.",
    "On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
    "On Windows type <ctrl> z then press Enter" );

    System.out.prin tf( "%s\n%s",
    "Enter account number (> 0), first name, last name and balance.",
    "? " );

    while ( input.hasNext() ) // loop until end-of-file indicator
    {
    try // output values to file
    {
    accountNumber = input.nextInt() ; // read account number
    firstName = input.next(); // read first name
    lastName = input.next(); // read last name
    balance = input.nextDoubl e(); // read balance

    if ( accountNumber > 0 )
    {
    // create new record
    record = new AccountRecordSe rializable( accountNumber,
    firstName, lastName, balance );
    output.writeObj ect( record ); // output record
    } // end if
    else
    {
    System.out.prin tln(
    "Account number must be greater than 0." );
    } // end else
    } // end try
    catch ( IOException ioException )
    {
    System.err.prin tln( "Error writing to file." );
    return;
    } // end catch
    catch ( NoSuchElementEx ception elementExceptio n )
    {
    System.err.prin tln( "Invalid input. Please try again." );
    input.nextLine( ); // discard input so user can try again
    } // end catch

    System.out.prin tf( "%s %s\n%s", "Enter account number (>0),",
    "first name, last name and balance.", "? " );
    } // end while
    } // end method addRecords

    // close file and terminate application
    public void closeFile()
    {
    try // close file
    {
    if ( output != null )
    output.close();
    } // end try
    catch ( IOException ioException )
    {
    System.err.prin tln( "Error closing file." );
    System.exit( 1 );
    } // end catch
    } // end method closeFile
    } // end class CreateSequentia lFile

    [/CODE]
    [CODE=java]

    import java.io.EOFExce ption;
    import java.io.FileInp utStream;
    import java.io.IOExcep tion;
    import java.io.ObjectI nputStream;

    import com.deitel.jhtp 7.ch14.AccountR ecordSerializab le;

    public class ReadSequentialF ile
    {
    private ObjectInputStre am input;

    // enable user to select file to open
    public void openFile()
    {
    try // open file
    {
    input = new ObjectInputStre am(
    new FileInputStream ( "clients.se r" ) );
    } // end try
    catch ( IOException ioException )
    {
    System.err.prin tln( "Error opening file." );
    } // end catch
    } // end method openFile

    // read record from file
    public void readRecords()
    {
    AccountRecordSe rializable record;
    System.out.prin tf( "%-10s%-12s%-12s%10s\n", "Account",
    "First Name", "Last Name", "Balance" );

    try // input the values from the file
    {
    while ( true )
    {
    record = ( AccountRecordSe rializable ) input.readObjec t();

    // display record contents
    System.out.prin tf( "%-10d%-12s%-12s%10.2f\n",
    record.getAccou nt(), record.getFirst Name(),
    record.getLastN ame(), record.getBalan ce() );
    } // end while
    } // end try
    catch ( EOFException endOfFileExcept ion )
    {
    return; // end of file was reached
    } // end catch
    catch ( ClassNotFoundEx ception classNotFoundEx ception )
    {
    System.err.prin tln( "Unable to create object." );
    } // end catch
    catch ( IOException ioException )
    {
    System.err.prin tln( "Error during reading from file." );
    } // end catch
    } // end method readRecords

    // close file and terminate application
    public void closeFile()
    {
    try // close file and exit
    {
    if ( input != null )
    input.close();
    System.exit( 0 );
    } // end try
    catch ( IOException ioException )
    {
    System.err.prin tln( "Error closing file." );
    System.exit( 1 );
    } // end catch
    } // end method closeFile
    } // end class ReadSequentialF ile

    [/CODE]
    what should i do to always read all records ?
    Don't you get an exception when you run this?
    Last edited by r035198x; Jun 11 '07, 10:08 AM. Reason: added code type to the code tags

    Comment

    • r035198x
      MVP
      • Sep 2006
      • 13225

      #3
      Originally posted by r035198x
      Don't you get an exception when you run this?
      Don't you get an exception when you run this?


      B.T.W: I've now switched to FF.

      Comment

      • dmjpro
        Top Contributor
        • Jan 2007
        • 2476

        #4
        Do close all the streams before reuse it.
        I think it ll help u.
        Best of luck.

        Kind regards,
        Dmjpro.

        Comment

        • JosAH
          Recognized Expert MVP
          • Mar 2007
          • 11453

          #5
          Originally posted by khajeddin
          hi:
          i have a program which should read and werite on a file but after the first time it writeon the file it can read te records.but other times it write on the file but just read the records which has written first time.
          Your problem is this: everytime you open an ObjectOutputStr eam the stream
          writes header information. When that is ready you can write objects to the
          stream.

          You do this: you open a file, write one object and close the file again. The file
          now contains this:

          HHHOOOOOOO ... OOO

          where the 'H's represent the header and the 'O' represents the serialized object.

          Then you do it again; the contents of the file now is:

          HHHOOOOOOO ... OOOHHHOOOOOOO ... OOO

          Where you expect your second object, a second header is written and when
          you attempt to read an object you'll get a exception telling you that the stream
          is corrupted.

          There are two solutions to this problem:

          1) you either keep your file and ObjectOutputStr eam open all the time so only
          when the ObjectOutputStr eam is created once that header will be written.

          or

          2) You implement this class:

          [code=java]
          public class YourObjectOutpu tStream extends ObjectOutputStr eam {

          private boolean header;

          public YourObjectOutpu tStream(OutputS tream out, boolean header) {
          super(out);
          this.header= header;
          }

          protected void writeStreamHead er() {

          if (header) super.writeStre amHeader();
          }
          }
          [/code]

          Only the first time you create your file you instantiate this class with the header
          flag set to true; all the other instantiations (when you reopen your file again) the
          header flag should be set to false. Read the API documentation for the description
          of the writeStreamHead er() method.

          kind regards,

          Jos

          Comment

          • r035198x
            MVP
            • Sep 2006
            • 13225

            #6
            Originally posted by JosAH
            Your problem is this: everytime you open an ObjectOutputStr eam the stream
            writes header information. When that is ready you can write objects to the
            stream.

            You do this: you open a file, write one object and close the file again. The file
            now contains this:

            HHHOOOOOOO ... OOO

            where the 'H's represent the header and the 'O' represents the serialized object.

            Then you do it again; the contents of the file now is:

            HHHOOOOOOO ... OOOHHHOOOOOOO ... OOO

            Where you expect your second object, a second header is written and when
            you attempt to read an object you'll get a exception telling you that the stream
            is corrupted.

            There are two solutions to this problem:

            1) you either keep your file and ObjectOutputStr eam open all the time so only
            when the ObjectOutputStr eam is created once that header will be written.

            or

            2) You implement this class:

            [code=java]
            public class YourObjectOutpu tStream extends ObjectOutputStr eam {

            private boolean header;

            public YourObjectOutpu tStream(OutputS tream out, boolean header) {
            super(out);
            this.header= header;
            }

            protected void writeStreamHead er() {

            if (header) super.writeStre amHeader();
            }
            }
            [/code]

            Only the first time you create your file you instantiate this class with the header
            flag set to true; all the other instantiations (when you reopen your file again) the
            header flag should be set to false. Read the API documentation for the description
            of the writeStreamHead er() method.

            kind regards,

            Jos
            And if they'd checked the console they'd have seen the exception ...

            Comment

            • JosAH
              Recognized Expert MVP
              • Mar 2007
              • 11453

              #7
              Originally posted by r035198x
              And if they'd checked the console they'd have seen the exception ...
              Well, this behaviour can look a bit obscure if one didn't read the API documentation
              for those ObjectStreams. People just happily hack away, expecting that all
              classes should work as they more or less think they should work; until something
              goes wrong: they simply panic then and don't read because they haven't read
              ever before ;-)

              kind regards,

              Jos

              Comment

              Working...