Java Reference
In-Depth Information
26. public String toString(){
27. return firstName + SPACE + lastName;
28. }
29. }
The DataCreator and DataRetriever classes are used to create and retrieve a test group of contacts for use in
the example.
Example A.114 DataCreator.java
1. import java.io.Serializable;
2. import java.io.ObjectOutputStream;
3. import java.io.FileOutputStream;
4. import java.io.IOException;
5. public class DataCreator{
6. private static final String DEFAULT_FILE = "data.ser";
7.
8. public static void main(String [] args){
9. String fileName;
10. if (args.length == 1){
11. fileName = args[0];
12 }
13. else{
14. fileName = DEFAULT_FILE;
15. }
16. serialize(fileName);
17. }
18.
19. public static void serialize(String fileName){
20. try{
21. serializeToFile(makeContactList(), fileName);
22. }
23. catch (IOException exc){
24. exc.printStackTrace();
25. }
26. }
27.
28. private static Serializable makeContactList(){
29. ContactList list = new ContactList();
30. list.addContact(new ContactImpl("David", "St. Hubbins", "Lead Guitar", "The New
Originals"));
31. list.addContact(new ContactImpl("Mick", "Shrimpton", "Drummer", "The New
Originals"));
32. list.addContact(new ContactImpl("Nigel", "Tufnel", "Lead Guitar", "The New
Originals"));
33. list.addContact(new ContactImpl("Derek", "Smalls", "Bass", "The New Originals"));
34. list.addContact(new ContactImpl("Viv", "Savage", "Keyboards", "The New
Originals"));
35. list.addContact(new ContactImpl("Nick", "Shrimpton", "CEO", "Fishy Business, LTD"));
36. list.addContact(new ContactImpl("Nickolai", "Lobachevski", "Senior Packer", "Fishy
Business, LTD"));
37. list.addContact(new ContactImpl("Alan", "Robertson", "Comptroller", "Universal
Exports"));
38. list.addContact(new ContactImpl("William", "Telle", "President", "Universal
Exports"));
39. list.addContact(new ContactImpl("Harvey", "Manfredjensenden", "Inspector",
"Universal Imports"));
40. list.addContact(new ContactImpl("Deirdre", "Pine", "Chief Mechanic", "The
Universal Joint"));
41. list.addContact(new ContactImpl("Martha", "Crump-Pinnett", "Lead Developer",
"Avatar Inc."));
42. list.addContact(new ContactImpl("Bryan", "Basham", "CTO", "IOVA"));
43. return list;
44. }
45.
46. private static void serializeToFile(Serializable content, String fileName) throws
IOException{
47. ObjectOutputStream serOut = new ObjectOutputStream(new FileOutputStream(fileName));
48. serOut.writeObject(content);
49. serOut.close();
50. }
51. }
Example A.115 DataRetriever.java
1. import java.io.File;
2. import java.io.FileInputStream;
3. import java.io.IOException;
Search WWH ::




Custom Search