Java Reference
In-Depth Information
Example A.71 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. }else{
13. fileName = DEFAULT_FILE;
14. }
15. serialize(fileName);
16. }
17.
18. public static void serialize(String fileName){
19. try{
20. serializeToFile(createData(), fileName);
21. } catch (IOException exc){
22. exc.printStackTrace();
23. }
24. }
25.
26. private static Serializable createData(){
27. ToDoListCollection data = new ToDoListCollectionImpl();
28. ToDoList listOne = new ToDoListImpl();
29. ToDoList listTwo = new ToDoListImpl();
30. ToDoList listThree = new ToDoListImpl();
31. listOne.setListName("Daily Routine");
32. listTwo.setListName("Programmer hair washing procedure");
33. listThree.setListName("Reading List");
34. listOne.add("Get up (harder some days than others)");
35. listOne.add("Brew cuppa Java");
36. listOne.add("Read JVM Times");
37. listTwo.add("Lather");
38. listTwo.add("Rinse");
39. listTwo.add("Repeat");
40. listTwo.add("(eventually throw a TooMuchHairConditioner exception)");
41. listThree.add("The complete annotated aphorisms of Duke");
42. listThree.add("How green was my Java");
43. listThree.add("URL, sweet URL");
44. data.add(listOne);
45. data.add(listTwo);
46. data.add(listThree);
47. return data;
48. }
49.
50. private static void serializeToFile(Serializable data, String fileName) throws IOException{
51. ObjectOutputStream serOut = new ObjectOutputStream(new FileOutputStream(fileName));
52. serOut.writeObject(data);
53. serOut.close();
54. }
55. }
Example A.72 DataRetriever.java
1. import java.io.File;
2. import java.io.FileInputStream;
3. import java.io.IOException;
4. import java.io.ObjectInputStream;
5.
6. public class DataRetriever{
7. public static Object deserializeData(String fileName){
8. Object returnValue = null;
9. try{
10. File inputFile = new File(fileName);
11. if (inputFile.exists() && inputFile.isFile()){
12. ObjectInputStream readIn = new ObjectInputStream(new FileInputStream(fileName));
13. returnValue = readIn.readObject();
14. readIn.close();
15. }else{
16. System.err.println("Unable to locate the file " + fileName);
17. }
18. }catch (ClassNotFoundException exc){
19. exc.printStackTrace();
Search WWH ::




Custom Search