Java Reference
In-Depth Information
FileInputStream istream = new FileInputStream("save.dat ");
ObjectInputStream oistream = new ObjectInputStream(istream);
// Read the data back, making sure the order is same as it was written.
i = oistream.readInt();
myValue = (String) oistream.readObject();
appData = (MyClass) oistream.readObject();
// Close the streams.
istream.close();
oistream.close();
Many streams have constructors that allow them to be instantiated with other
streams of the same type. In this case, both ObjectInputStream and ObjectOutput-
Stream were instantiated with corresponding file streams. If you are reading or writ-
ing large amounts of data, you will want to create buffered streams in this manner.
R EADERS AND W RITERS
The InputStream and OutputStream classes are for reading and writing byte streams.
As discussed in Chapter 8, Java stores strings and characters in a double-byte Uni-
code format. Text files, as stored and manipulated by most editors, treat characters
as single bytes of data. The alert reader can see problems in all of this. How does
Java transform single bytes into double bytes? What is the extra byte for in the Uni-
code format?
In most cases, we in the Western world never have problems with any of this.
We use an extended ASCII character set with character values ranging from 0 to 255
(some of the characters are control characters or are unprintable, or both). In Uni-
code, the extra byte represents the character set, and the value of the extended
ASCII character set is 0. To transform the ASCII letter A, hexadecimal value 0x41,
into double-byte format, you simply place a byte of value zero in front of it, 0x0041.
In transforming the A back to single-byte format, you remove the leading zero.
What would happen, however, if someone created a file on a system using a dif-
ferent character set and shipped it to us? The Reader and Writer classes are the par-
ent classes for resolving these problems. Reader s and Writer s are used for reading
and writing text files. Unless you deal with communications from countries using
non-European languages, you will probably never have to use the character set con-
version features that the Reader and Writer classes support. As a knowledgeable pro-
grammer, you need to know that the support is present if you need it. Otherwise,
you can take advantage of the API that facilitates ordinary text input and output.
Search WWH ::




Custom Search