|
|
|
|||
|
Using DataInputStream and DataOutputStreamThis page shows you how to use thejava.io
DataInputStreamDataOutputStream19.99 12 Java T-shirt 9.99 8 Java Mug DataOutputStream, like other filtered output streams, must be attached to some
other OutputStream. In this case, it's attached to a FileOutputStream that's set up
to write to a file named invoice1.txt.
Next, DataIOTest uses DataOutputStream's specialized writeXXX
methods to write the invoice data (contained within arrays in the program)
according to the type of data being written:
Note that this code snippet closes the output stream when it's finished.
Next,
DataInputStream also must be attached to some other InputStream;
in this case, a FileInputStream set up
to read the file just written--invoice1.txt.
DataIOTest then just reads the data back in using DataInputStream's
specialized readXXX methods.
When all of the data has been read, DataIOTest displays a statement
summarizing the order and the total amount owed, and closes the stream.
Note the loop that
The readLine method returns a value, null, that indicates that
the end of the file has been reached. Many of the DataInputStream readXXX
methods can't do this because any value that could be returned to indicate end-of-file
may also be a legitimate value read from the stream. For example, suppose that you
wanted to use -1 to indicate end-of-file? Well, you can't because -1 is a legitimate
value that can be read from the input stream using readDouble,
readInt, or one of the other read methods that reads numbers.
So DataInputStream's readXXX methods throw an EOFException instead.
When the EOFException occurs the while (true) terminates.
When you run the You've ordered 12 units of Java T-shirt at $19.99 You've ordered 8 units of Java Mug at $9.99 You've ordered 13 units of Duke Juggling Dolls at $15.99 You've ordered 29 units of Java Pin at $3.99 You've ordered 50 units of Java Key Chain at $4.99 For a TOTAL of: $892.88 | |||
|