473,625 Members | 3,264 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

ObjectInput Stream & objectOutputStr eam

51 New Member
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:
Expand|Select|Wrap|Line Numbers
  1.  
  2. import java.io.FileOutputStream;
  3. import java.io.IOException;
  4. import java.io.ObjectOutputStream;
  5. import java.util.NoSuchElementException;
  6. import java.util.Scanner;
  7.  
  8. import com.deitel.jhtp7.ch14.AccountRecordSerializable;
  9.  
  10. public class CreateSequentialFile
  11. {
  12.    private ObjectOutputStream output; // outputs data to file
  13.  
  14.    // allow user to specify file name
  15.    public void openFile()
  16.    {
  17.       try // open file
  18.       {
  19.          output = new ObjectOutputStream(
  20.             new FileOutputStream( "clients.ser" ,true) );
  21.       } // end try
  22.       catch ( IOException ioException )
  23.       {
  24.          System.err.println( "Error opening file." );
  25.       } // end catch
  26.    } // end method openFile
  27.  
  28.    // add records to file
  29.    public void addRecords()
  30.    {
  31.       AccountRecordSerializable record; // object to be written to file
  32.       int accountNumber = 0; // account number for record object
  33.       String firstName; // first name for record object
  34.       String lastName; // last name for record object
  35.       double balance; // balance for record object
  36.  
  37.       Scanner input = new Scanner( System.in );
  38.  
  39.       System.out.printf( "%s\n%s\n%s\n%s\n\n",
  40.          "To terminate input, type the end-of-file indicator ",
  41.          "when you are prompted to enter input.",
  42.          "On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
  43.          "On Windows type <ctrl> z then press Enter" );
  44.  
  45.       System.out.printf( "%s\n%s", 
  46.          "Enter account number (> 0), first name, last name and balance.",
  47.          "? " );
  48.  
  49.       while ( input.hasNext() ) // loop until end-of-file indicator
  50.       {
  51.          try // output values to file
  52.          {
  53.             accountNumber = input.nextInt(); // read account number
  54.             firstName = input.next(); // read first name
  55.             lastName = input.next(); // read last name
  56.             balance = input.nextDouble(); // read balance
  57.  
  58.             if ( accountNumber > 0 )
  59.             {
  60.                // create new record
  61.                record = new AccountRecordSerializable( accountNumber,
  62.                   firstName, lastName, balance );
  63.                output.writeObject( record ); // output record
  64.             } // end if
  65.             else
  66.             {
  67.                System.out.println(
  68.                   "Account number must be greater than 0." );
  69.             } // end else
  70.          } // end try
  71.          catch ( IOException ioException )
  72.          {
  73.             System.err.println( "Error writing to file." );
  74.             return;
  75.          } // end catch
  76.          catch ( NoSuchElementException elementException )
  77.          {
  78.             System.err.println( "Invalid input. Please try again." );
  79.             input.nextLine(); // discard input so user can try again
  80.          } // end catch
  81.  
  82.          System.out.printf( "%s %s\n%s", "Enter account number (>0),",
  83.             "first name, last name and balance.", "? " );
  84.       } // end while
  85.    } // end method addRecords
  86.  
  87.    // close file and terminate application 
  88.    public void closeFile() 
  89.    {
  90.       try // close file
  91.       {
  92.          if ( output != null )
  93.             output.close();
  94.       } // end try
  95.       catch ( IOException ioException )
  96.       {
  97.          System.err.println( "Error closing file." );
  98.          System.exit( 1 );
  99.       } // end catch
  100.    } // end method closeFile
  101. } // end class CreateSequentialFile
  102.  
  103.  
Expand|Select|Wrap|Line Numbers
  1.  
  2. import java.io.EOFException;
  3. import java.io.FileInputStream;
  4. import java.io.IOException;
  5. import java.io.ObjectInputStream;
  6.  
  7. import com.deitel.jhtp7.ch14.AccountRecordSerializable;
  8.  
  9. public class ReadSequentialFile
  10. {
  11.    private ObjectInputStream input;
  12.  
  13.    // enable user to select file to open
  14.    public void openFile()
  15.    {
  16.       try // open file
  17.       {
  18.          input = new ObjectInputStream(
  19.             new FileInputStream( "clients.ser" ) );
  20.       } // end try
  21.       catch ( IOException ioException )
  22.       {
  23.          System.err.println( "Error opening file." );
  24.       } // end catch
  25.    } // end method openFile
  26.  
  27.    // read record from file
  28.    public void readRecords()
  29.    {
  30.       AccountRecordSerializable record;
  31.       System.out.printf( "%-10s%-12s%-12s%10s\n", "Account",
  32.          "First Name", "Last Name", "Balance" );
  33.  
  34.       try // input the values from the file
  35.       { 
  36.          while ( true )
  37.          {
  38.             record = ( AccountRecordSerializable ) input.readObject();
  39.  
  40.             // display record contents
  41.             System.out.printf( "%-10d%-12s%-12s%10.2f\n",
  42.                record.getAccount(), record.getFirstName(),
  43.                record.getLastName(), record.getBalance() );
  44.          } // end while
  45.       } // end try
  46.       catch ( EOFException endOfFileException )
  47.       {
  48.          return; // end of file was reached
  49.       } // end catch
  50.       catch ( ClassNotFoundException classNotFoundException )
  51.       {
  52.          System.err.println( "Unable to create object." );
  53.       } // end catch
  54.       catch ( IOException ioException )
  55.       {
  56.          System.err.println( "Error during reading from file." );
  57.       } // end catch
  58.    } // end method readRecords
  59.  
  60.    // close file and terminate application
  61.    public void closeFile()
  62.    {
  63.       try // close file and exit
  64.       {
  65.          if ( input != null )
  66.             input.close();
  67.          System.exit( 0 );
  68.       } // end try
  69.       catch ( IOException ioException )
  70.       {
  71.          System.err.println( "Error closing file." );
  72.          System.exit( 1 );
  73.       } // end catch
  74.    } // end method closeFile
  75. } // end class ReadSequentialFile
  76.  
  77.  
what should i do to always read all records ?
Jun 11 '07 #1
6 3053
r035198x
13,262 MVP
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:
Expand|Select|Wrap|Line Numbers
  1.  
  2. import java.io.FileOutputStream;
  3. import java.io.IOException;
  4. import java.io.ObjectOutputStream;
  5. import java.util.NoSuchElementException;
  6. import java.util.Scanner;
  7.  
  8. import com.deitel.jhtp7.ch14.AccountRecordSerializable;
  9.  
  10. public class CreateSequentialFile
  11. {
  12. private ObjectOutputStream output; // outputs data to file
  13.  
  14. // allow user to specify file name
  15. public void openFile()
  16. {
  17. try // open file
  18. {
  19. output = new ObjectOutputStream(
  20. new FileOutputStream( "clients.ser" ,true) );
  21. } // end try
  22. catch ( IOException ioException )
  23. {
  24. System.err.println( "Error opening file." );
  25. } // end catch
  26. } // end method openFile
  27.  
  28. // add records to file
  29. public void addRecords()
  30. {
  31. AccountRecordSerializable record; // object to be written to file
  32. int accountNumber = 0; // account number for record object
  33. String firstName; // first name for record object
  34. String lastName; // last name for record object
  35. double balance; // balance for record object
  36.  
  37. Scanner input = new Scanner( System.in );
  38.  
  39. System.out.printf( "%s\n%s\n%s\n%s\n\n",
  40. "To terminate input, type the end-of-file indicator ",
  41. "when you are prompted to enter input.",
  42. "On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
  43. "On Windows type <ctrl> z then press Enter" );
  44.  
  45. System.out.printf( "%s\n%s", 
  46. "Enter account number (> 0), first name, last name and balance.",
  47. "? " );
  48.  
  49. while ( input.hasNext() ) // loop until end-of-file indicator
  50. {
  51. try // output values to file
  52. {
  53. accountNumber = input.nextInt(); // read account number
  54. firstName = input.next(); // read first name
  55. lastName = input.next(); // read last name
  56. balance = input.nextDouble(); // read balance
  57.  
  58. if ( accountNumber > 0 )
  59. {
  60. // create new record
  61. record = new AccountRecordSerializable( accountNumber,
  62. firstName, lastName, balance );
  63. output.writeObject( record ); // output record
  64. } // end if
  65. else
  66. {
  67. System.out.println(
  68. "Account number must be greater than 0." );
  69. } // end else
  70. } // end try
  71. catch ( IOException ioException )
  72. {
  73. System.err.println( "Error writing to file." );
  74. return;
  75. } // end catch
  76. catch ( NoSuchElementException elementException )
  77. {
  78. System.err.println( "Invalid input. Please try again." );
  79. input.nextLine(); // discard input so user can try again
  80. } // end catch
  81.  
  82. System.out.printf( "%s %s\n%s", "Enter account number (>0),",
  83. "first name, last name and balance.", "? " );
  84. } // end while
  85. } // end method addRecords
  86.  
  87. // close file and terminate application 
  88. public void closeFile() 
  89. {
  90. try // close file
  91. {
  92. if ( output != null )
  93. output.close();
  94. } // end try
  95. catch ( IOException ioException )
  96. {
  97. System.err.println( "Error closing file." );
  98. System.exit( 1 );
  99. } // end catch
  100. } // end method closeFile
  101. } // end class CreateSequentialFile
  102.  
  103.  
Expand|Select|Wrap|Line Numbers
  1.  
  2. import java.io.EOFException;
  3. import java.io.FileInputStream;
  4. import java.io.IOException;
  5. import java.io.ObjectInputStream;
  6.  
  7. import com.deitel.jhtp7.ch14.AccountRecordSerializable;
  8.  
  9. public class ReadSequentialFile
  10. {
  11. private ObjectInputStream input;
  12.  
  13. // enable user to select file to open
  14. public void openFile()
  15. {
  16. try // open file
  17. {
  18. input = new ObjectInputStream(
  19. new FileInputStream( "clients.ser" ) );
  20. } // end try
  21. catch ( IOException ioException )
  22. {
  23. System.err.println( "Error opening file." );
  24. } // end catch
  25. } // end method openFile
  26.  
  27. // read record from file
  28. public void readRecords()
  29. {
  30. AccountRecordSerializable record;
  31. System.out.printf( "%-10s%-12s%-12s%10s\n", "Account",
  32. "First Name", "Last Name", "Balance" );
  33.  
  34. try // input the values from the file
  35. while ( true )
  36. {
  37. record = ( AccountRecordSerializable ) input.readObject();
  38.  
  39. // display record contents
  40. System.out.printf( "%-10d%-12s%-12s%10.2f\n",
  41. record.getAccount(), record.getFirstName(),
  42. record.getLastName(), record.getBalance() );
  43. } // end while
  44. } // end try
  45. catch ( EOFException endOfFileException )
  46. {
  47. return; // end of file was reached
  48. } // end catch
  49. catch ( ClassNotFoundException classNotFoundException )
  50. {
  51. System.err.println( "Unable to create object." );
  52. } // end catch
  53. catch ( IOException ioException )
  54. {
  55. System.err.println( "Error during reading from file." );
  56. } // end catch
  57. } // end method readRecords
  58.  
  59. // close file and terminate application
  60. public void closeFile()
  61. {
  62. try // close file and exit
  63. {
  64. if ( input != null )
  65. input.close();
  66. System.exit( 0 );
  67. } // end try
  68. catch ( IOException ioException )
  69. {
  70. System.err.println( "Error closing file." );
  71. System.exit( 1 );
  72. } // end catch
  73. } // end method closeFile
  74. } // end class ReadSequentialFile
  75.  
  76.  
what should i do to always read all records ?
Don't you get an exception when you run this?
Jun 11 '07 #2
r035198x
13,262 MVP
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.
Jun 11 '07 #3
dmjpro
2,476 Top Contributor
Do close all the streams before reuse it.
I think it ll help u.
Best of luck.

Kind regards,
Dmjpro.
Jun 11 '07 #4
JosAH
11,448 Recognized Expert MVP
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:

Expand|Select|Wrap|Line Numbers
  1. public class YourObjectOutputStream extends ObjectOutputStream {
  2.  
  3.    private boolean header;
  4.  
  5.    public YourObjectOutputStream(OutputStream out, boolean header) { 
  6.       super(out); 
  7.       this.header= header;
  8.    }
  9.  
  10.    protected void writeStreamHeader() {
  11.  
  12.       if (header) super.writeStreamHeader(); 
  13.    }
  14. }
  15.  
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
Jun 11 '07 #5
r035198x
13,262 MVP
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:

Expand|Select|Wrap|Line Numbers
  1. public class YourObjectOutputStream extends ObjectOutputStream {
  2.  
  3.    private boolean header;
  4.  
  5.    public YourObjectOutputStream(OutputStream out, boolean header) { 
  6.       super(out); 
  7.       this.header= header;
  8.    }
  9.  
  10.    protected void writeStreamHeader() {
  11.  
  12.       if (header) super.writeStreamHeader(); 
  13.    }
  14. }
  15.  
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 ...
Jun 11 '07 #6
JosAH
11,448 Recognized Expert MVP
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
Jun 11 '07 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

2
10450
by: Maria Gaitani | last post by:
Hi! I have made a client and a server which are supposed to communicate by sending java objects. They don't. I have managed to send an object from the client to the server. But continuing after that I can't do the opposite. I want the program to send an object-reply from the server to the client. But on this step boths sides throw a socket exception. From println's I have figured out that it can't set up on either side the...
2
47261
by: SubbaRao Karanam | last post by:
What does this error for the Code below java.io.StreamCorruptedException: invalid stream header at java.io.ObjectInputStream.readStreamHeader(Unknown Source) at java.io.ObjectInputStream.<init>(Unknown Source) at com.kbs.framework.client.gui.PIPReport.doProcess(PIPReport.java:562) at com.kbs.framework.client.gui.PIPReport.actionPerformed(PIPReport.java:508) at javax.swing.AbstractButton.fireActionPerformed(Unknown Source) at...
6
3877
by: Kiran Kumar Kamineni | last post by:
Do I have to implement the serializable interface? Is the default implementation of the serializable interface enough?
1
26722
by: andrewcw | last post by:
OK I am half way there - I can manipulate the stream without the byte issue like this - but is this the way to push the new values back into the stream & write out the stream without resorting to byte conversion ?? FileStream stream = null; stream = File.Open(fiPath, FileMode.Open, FileAccess.ReadWrite,FileShare.None); System.IO.StreamReader Tin = new System.IO.StreamReader (stream);
1
1735
by: Guy Korland | last post by:
Hi, 1. How can I read stream in blocking mode? Meaning stop the thread till it get a new line sign? Or getting an event from the stream on new income data? 2. How can I convert 2 bytes to char?
16
9095
by: Ali | last post by:
Hi I want to write (or read) to a stream, but the data is not byte array I converted the data to byte array manually, but it is very slow, (becuse the data is very large) Is another way for this kind of writing and reading best regard Ali.
1
4313
by: Kannan T via .NET 247 | last post by:
Hi All, Is there any equivalent C# method for reset method of ObjectOutputStream in Java If so do let me know. Advance Thanks ! ! ! -------------------------------- From: Kannan T ----------------------- Posted by a user from .NET 247 (http://www.dotnet247.com/)
2
1603
by: CindyH | last post by:
Hi I have an xml stream that I would like to read with xmltextreader. Problem is that there are some & inside the xml stream. Parse is not working on them. Can someone show me sample code for reading a stream like this? Thanks, Cindy
1
3082
by: MiziaQ | last post by:
I have this code to write to a file. However, this only saves one entry. How can I save multiple entries, each saved in separate lines ? At this point the output in the .txt file is strange: ’ t Peter|t Pan|t 01/09/67|t 098 1456789|t 18-Mar-2009|t Male Surgical Wardt  I need the text to be clear in order to read it in a JTable public void writeTable() {
0
8256
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8497
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7184
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6118
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5570
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4193
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2621
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1803
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1500
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.