Java Reference
In-Depth Information
The ContactManager program writes the fi elds of a Contact object to a given File , and
also reads the fi elds from a File and creates new Contact objects with the read data. Study
the code and see if you can determine its output:
1. package com.sybex.io;
2.
3. import java.io.*;
4. import java.util.ArrayList;
5.
6. public class ContactManager {
7.
8. public static void addContact(Contact contact, File dest)
9. throws IOException {
10. FileOutputStream fos = new FileOutputStream(dest, true);
11. BufferedOutputStream bos = new BufferedOutputStream(fos);
12. DataOutputStream out = new DataOutputStream(bos);
13. out.writeUTF(contact.name);
14. out.writeInt(contact.age);
15. out.writeLong(contact.cellPhone);
16. out.close();
17. bos.close();
18. fos.close();
19. }
20.
21. public static ArrayList<Contact> getContacts(File source)
22. throws IOException {
23. ArrayList<Contact> contacts = new ArrayList<Contact>();
24.
25. FileInputStream fis = new FileInputStream(source);
26. BufferedInputStream bis = new BufferedInputStream(fis);
27. DataInputStream in = new DataInputStream(bis);
28. while(in.available() > 0) {
29. String name = in.readUTF();
30. int age = in.readInt();
31. long cellPhone = in.readLong();
32. Contact current = new Contact(name, age, cellPhone);
33. contacts.add(current);
34. }
35.
36. return contacts;
37. }
Search WWH ::




Custom Search