Java Reference
In-Depth Information
10. The while loop on line 28 repeats until all the data is read from the file. For each set
of data in the file, a Contact object is instantiated and added to the ArrayList , which
is returned on line 36 and printed to the console on line 50. The toString method is
invoked on each Contact and printed to the console.
The output of the ContactManager program is
[Bugs Bunny 22 2025551212
, Daffy Duck 33 3035551212
]
The square brackets and comma in the output of ContactManager are
the output of the ArrayList object. The toString method of ArrayList
returns the elements of the collection in a comma-separated list, which
is useful for debugging but probably not something you will use in a
production scenario.
I doubt anyone would use the ContactManager program to actually manage your con-
tacts in real life, but it does demonstrate a typical use of the classes in the java.io package:
chaining streams together to buffer and fi lter the data into whatever format your program
needs.
You might be tempted to write code like ContactManager that writes the fi elds of an
object to a fi le. It seems like a good way to save the state of your objects, and it would make
sense to do this except for the fact that Java has a built-in mechanism called serialization
for saving the state of objects. In the upcoming section “Object Serialization,” I provide
a different version of ContactManager that writes Contact objects to a fi le in an easier
fashion.
The next section discusses a stream that is both a low-level and a high-level stream: the
PrintWriter class.
The PrintWriter Class
The purpose of a PrintWriter object is to print data types and objects to a character
stream. The PrintWriter class contains the same print and println methods as
PrintStream (the data type of System.out and System.err ), except that PrintWriter
outputs data as characters instead of bytes.
Let's start with a simple example of using PrintWriter to print data types to a fi le as
characters. See if you can determine the result of the following statements:
6. int i = 101;
7. double d = 1.0/3.0;
8. StringBuilder s = new StringBuilder(“hello”);
9. boolean b = true;
10.
Search WWH ::




Custom Search