Re: Project5Read
On Thu, 09 Jul 2009 12:06:56 -0400, "John B. Matthews"
<nospam@nospam.invalid> wrote:
In article
<6ef5e6dd-0da7-45ac-85d7-548f119b29e3@t13g2000yqt.googlegroups.com>,
matt <mweppler@gmail.com> wrote:
With Project5Write I am creating binary data using writeUTF and
writeInt. When it comes to Project5Read I would like to read the data
using readUTF and readInt one record at a time. I thought the while
((c = istream.read()) != -1) would accomplish this but what I really
need in the while loop is a way to read each record and then go to the
next and so on. I wish I could explain myself better but at this point
Im just unsure of a number of things with programming.
Here is the dat file when opened with a text editor:
I was curious what a DataOutputStream looked like inside:
$ hd test.dat
0000: 00 0a 4a 6f 68 6e 20 53 6d 69 74 68 00 05 53 61 ..John Smith..Sa
0010: 6c 65 73 00 00 00 0f 00 0a 46 72 65 64 20 44 61 les......Fred Da
0020: 72 6d 65 00 08 53 65 63 75 72 69 74 79 00 00 00 rme..Security...
0030: 14 00 11 41 6e 6e 65 20 55 75 6d 65 6c 6c 6d 61 ...Anne Uumellma
0040: 68 61 79 65 00 09 4e 65 75 72 6f 6c 6f 67 79 00 haye..Neurology.
0050: 00 00 19 ...
Well, you _could_ catch the EOFException to exit the loop, but that's
considered bad form. If only DataInputStream had a way to determine if
there was more data "available", perhaps something inherited from it's
superclass:
<http://java.sun.com/javase/6/docs/api/java/io/FilterInputStream.html>
No joy. According to the Sun tutorials that standard way to detect
EoF is to catch an EoF exception.
http://www.j2ee.me/docs/books/tutorial/essential/io/datastreams.html
"Notice that DataStreams detects an end-of-file condition by catching
EOFException, instead of testing for an invalid return value. All
implementations of DataInput methods use EOFException instead of
return values."
The sample code looks like:
try {
while (true) {
price = in.readDouble();
unit = in.readInt();
desc = in.readUTF();
System.out.format("You ordered %d units of %s at $%.2f%n",
unit, desc, price);
total += unit * price;
}
} catch (EOFException e) {
}
Clunky, but it looks like the only way to do it. Ugh. Now I know why
I usually use text streams rather than data streams.
Better to amend Project5Write to output the number of records in the
file and to use that to determine EoF.
rossum