Java Reference
In-Depth Information
38.
39. public static void main(String [] args) {
40. try {
41. Contact one = new Contact(“Bugs Bunny”, 22,
42. 2025551212L);
43. Contact two = new Contact(“Daffy Duck”, 33,
44. 3035551212L);
45. File contactsFile = new File(“mycontacts.dat”);
46.
47. addContact(one, contactsFile);
48. addContact(two, contactsFile);
49.
50. System.out.println(getContacts(contactsFile));
51. }catch(IOException e) {
52. e.printStackTrace();
53. }
54. }
55. }
Let's step through the ContactManager program and discuss what it does:
1. Within main , two Contact objects are instantiated on lines 41-44.
2. The File object on line 45 represents the pathname to the file that we will be writing
to and reading from, which is mycontacts.dat .
3. The addContact method is invoked on line 47, passing in the Bugs Bunny object.
Within addContact , a FileOutputStream is instantiated on line 10 using mycontacts
.dat . The true argument says to append to the file. Without the true argument, any
existing data in the file is lost.
4. Line 11 chains a BufferedOutputStream to the FileOutputStream and line 12 chains
a DataOutputStream to the buffer.
5. The writeUTF method is for writing String objects, and on line 13 ”Bugs Bunny”
is written to the file. Similarly, the int 22 is written on line 14 and the long
2025551212 is written on line 15.
6. The streams are closed and the method returns. The process repeats for Daffy Duck
on line 48.
7. Line 50 invokes the getContacts method for mycontacts.dat , so control jumps to
line 21.
8. Lines 25-27 chain together the streams to read, buffer, and filter the data in
mycontacts.dat through a DataInputStream .
9. Lines 29-31 read in the data in the same order that it was written, and the data is
used to instantiate a new Contact object. Line 33 adds the Contact object to the
ArrayList from line 23.
Search WWH ::




Custom Search