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: -
-
import java.io.FileOutputStream;
-
import java.io.IOException;
-
import java.io.ObjectOutputStream;
-
import java.util.NoSuchElementException;
-
import java.util.Scanner;
-
-
import com.deitel.jhtp7.ch14.AccountRecordSerializable;
-
-
public class CreateSequentialFile
-
{
-
private ObjectOutputStream output; // outputs data to file
-
-
// allow user to specify file name
-
public void openFile()
-
{
-
try // open file
-
{
-
output = new ObjectOutputStream(
-
new FileOutputStream( "clients.ser" ,true) );
-
} // end try
-
catch ( IOException ioException )
-
{
-
System.err.println( "Error opening file." );
-
} // end catch
-
} // end method openFile
-
-
// add records to file
-
public void addRecords()
-
{
-
AccountRecordSerializable 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.printf( "%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.printf( "%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.nextDouble(); // read balance
-
-
if ( accountNumber > 0 )
-
{
-
// create new record
-
record = new AccountRecordSerializable( accountNumber,
-
firstName, lastName, balance );
-
output.writeObject( record ); // output record
-
} // end if
-
else
-
{
-
System.out.println(
-
"Account number must be greater than 0." );
-
} // end else
-
} // end try
-
catch ( IOException ioException )
-
{
-
System.err.println( "Error writing to file." );
-
return;
-
} // end catch
-
catch ( NoSuchElementException elementException )
-
{
-
System.err.println( "Invalid input. Please try again." );
-
input.nextLine(); // discard input so user can try again
-
} // end catch
-
-
System.out.printf( "%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.println( "Error closing file." );
-
System.exit( 1 );
-
} // end catch
-
} // end method closeFile
-
} // end class CreateSequentialFile
-
-
-
-
import java.io.EOFException;
-
import java.io.FileInputStream;
-
import java.io.IOException;
-
import java.io.ObjectInputStream;
-
-
import com.deitel.jhtp7.ch14.AccountRecordSerializable;
-
-
public class ReadSequentialFile
-
{
-
private ObjectInputStream input;
-
-
// enable user to select file to open
-
public void openFile()
-
{
-
try // open file
-
{
-
input = new ObjectInputStream(
-
new FileInputStream( "clients.ser" ) );
-
} // end try
-
catch ( IOException ioException )
-
{
-
System.err.println( "Error opening file." );
-
} // end catch
-
} // end method openFile
-
-
// read record from file
-
public void readRecords()
-
{
-
AccountRecordSerializable record;
-
System.out.printf( "%-10s%-12s%-12s%10s\n", "Account",
-
"First Name", "Last Name", "Balance" );
-
-
try // input the values from the file
-
{
-
while ( true )
-
{
-
record = ( AccountRecordSerializable ) input.readObject();
-
-
// display record contents
-
System.out.printf( "%-10d%-12s%-12s%10.2f\n",
-
record.getAccount(), record.getFirstName(),
-
record.getLastName(), record.getBalance() );
-
} // end while
-
} // end try
-
catch ( EOFException endOfFileException )
-
{
-
return; // end of file was reached
-
} // end catch
-
catch ( ClassNotFoundException classNotFoundException )
-
{
-
System.err.println( "Unable to create object." );
-
} // end catch
-
catch ( IOException ioException )
-
{
-
System.err.println( "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.println( "Error closing file." );
-
System.exit( 1 );
-
} // end catch
-
} // end method closeFile
-
} // end class ReadSequentialFile
-
-
what should i do to always read all records ?
6 3053
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: -
-
import java.io.FileOutputStream;
-
import java.io.IOException;
-
import java.io.ObjectOutputStream;
-
import java.util.NoSuchElementException;
-
import java.util.Scanner;
-
-
import com.deitel.jhtp7.ch14.AccountRecordSerializable;
-
-
public class CreateSequentialFile
-
{
-
private ObjectOutputStream output; // outputs data to file
-
-
// allow user to specify file name
-
public void openFile()
-
{
-
try // open file
-
{
-
output = new ObjectOutputStream(
-
new FileOutputStream( "clients.ser" ,true) );
-
} // end try
-
catch ( IOException ioException )
-
{
-
System.err.println( "Error opening file." );
-
} // end catch
-
} // end method openFile
-
-
// add records to file
-
public void addRecords()
-
{
-
AccountRecordSerializable 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.printf( "%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.printf( "%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.nextDouble(); // read balance
-
-
if ( accountNumber > 0 )
-
{
-
// create new record
-
record = new AccountRecordSerializable( accountNumber,
-
firstName, lastName, balance );
-
output.writeObject( record ); // output record
-
} // end if
-
else
-
{
-
System.out.println(
-
"Account number must be greater than 0." );
-
} // end else
-
} // end try
-
catch ( IOException ioException )
-
{
-
System.err.println( "Error writing to file." );
-
return;
-
} // end catch
-
catch ( NoSuchElementException elementException )
-
{
-
System.err.println( "Invalid input. Please try again." );
-
input.nextLine(); // discard input so user can try again
-
} // end catch
-
-
System.out.printf( "%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.println( "Error closing file." );
-
System.exit( 1 );
-
} // end catch
-
} // end method closeFile
-
} // end class CreateSequentialFile
-
-
-
-
import java.io.EOFException;
-
import java.io.FileInputStream;
-
import java.io.IOException;
-
import java.io.ObjectInputStream;
-
-
import com.deitel.jhtp7.ch14.AccountRecordSerializable;
-
-
public class ReadSequentialFile
-
{
-
private ObjectInputStream input;
-
-
// enable user to select file to open
-
public void openFile()
-
{
-
try // open file
-
{
-
input = new ObjectInputStream(
-
new FileInputStream( "clients.ser" ) );
-
} // end try
-
catch ( IOException ioException )
-
{
-
System.err.println( "Error opening file." );
-
} // end catch
-
} // end method openFile
-
-
// read record from file
-
public void readRecords()
-
{
-
AccountRecordSerializable record;
-
System.out.printf( "%-10s%-12s%-12s%10s\n", "Account",
-
"First Name", "Last Name", "Balance" );
-
-
try // input the values from the file
-
{
-
while ( true )
-
{
-
record = ( AccountRecordSerializable ) input.readObject();
-
-
// display record contents
-
System.out.printf( "%-10d%-12s%-12s%10.2f\n",
-
record.getAccount(), record.getFirstName(),
-
record.getLastName(), record.getBalance() );
-
} // end while
-
} // end try
-
catch ( EOFException endOfFileException )
-
{
-
return; // end of file was reached
-
} // end catch
-
catch ( ClassNotFoundException classNotFoundException )
-
{
-
System.err.println( "Unable to create object." );
-
} // end catch
-
catch ( IOException ioException )
-
{
-
System.err.println( "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.println( "Error closing file." );
-
System.exit( 1 );
-
} // end catch
-
} // end method closeFile
-
} // end class ReadSequentialFile
-
-
what should i do to always read all records ?
Don't you get an exception when you run this?
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.
Do close all the streams before reuse it.
I think it ll help u.
Best of luck.
Kind regards,
Dmjpro.
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: -
public class YourObjectOutputStream extends ObjectOutputStream {
-
-
private boolean header;
-
-
public YourObjectOutputStream(OutputStream out, boolean header) {
-
super(out);
-
this.header= header;
-
}
-
-
protected void writeStreamHeader() {
-
-
if (header) super.writeStreamHeader();
-
}
-
}
-
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
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: -
public class YourObjectOutputStream extends ObjectOutputStream {
-
-
private boolean header;
-
-
public YourObjectOutputStream(OutputStream out, boolean header) {
-
super(out);
-
this.header= header;
-
}
-
-
protected void writeStreamHeader() {
-
-
if (header) super.writeStreamHeader();
-
}
-
}
-
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 ...
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
Sign in to post your reply or Sign up for a free account.
Similar topics |
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...
|
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...
|
by: Kiran Kumar Kamineni |
last post by:
Do I have to implement the serializable interface?
Is the default implementation of the serializable interface enough?
|
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);
|
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?
| |
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.
|
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/)
|
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
|
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() {
|
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...
|
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...
| |
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...
|
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...
|
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();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |