Java Reference
In-Depth Information
8. public class DataCreator{
9. private static final String DEFAULT_FILE = "data.ser";
10. private static Calendar dateCreator = Calendar.getInstance();
11.
12. public static void main(String [] args){
13. String fileName;
14. if (args.length == 1){
15. fileName = args[0];
16. }
17. else{
18. fileName = DEFAULT_FILE;
19. }
20. serialize(fileName);
21. }
22.
23. public static void serialize(String fileName){
24. try{
25. serializeToFile(createData(), fileName);
26. }
27. catch (IOException exc){
28. exc.printStackTrace();
29. }
30. }
31.
32. private static Serializable createData(){
33. ArrayList appointments = new ArrayList();
34. ArrayList contacts = new ArrayList();
35. contacts.add(new ContactImpl("Test", "Subject", "Volunteer", "United Patterns
Consortium"));
36. Location location1 = new LocationImpl("Punxsutawney, PA");
37. appointments.add(new Appointment("Slowpokes anonymous", contacts, location1,
createDate(2001, 1, 1, 12, 01), createDate(2001, 1, 1, 12, 02)));
38. appointments.add(new Appointment("Java focus group", contacts, location1,
createDate(2001, 1, 1, 12, 30), createDate(2001, 1, 1, 14, 30)));
39. appointments.add(new Appointment("Something else", contacts, location1,
createDate(2001, 1, 1, 12, 01), createDate(2001, 1, 1, 12, 02)));
40. appointments.add(new Appointment("Yet another thingie", contacts, location1,
createDate(2001, 1, 1, 12, 01), createDate(2001, 1, 1, 12, 02)));
41. return appointments;
42. }
43.
44. private static void serializeToFile(Serializable content, String fileName) throws
IOException{
45. ObjectOutputStream serOut = new ObjectOutputStream(new FileOutputStream(fileName));
46. serOut.writeObject(content);
47. serOut.close();
48. }
49.
50. public static Date createDate(int year, int month, int day, int hour, int minute){
51. dateCreator.set(year, month, day, hour, minute);
52. return dateCreator.getTime();
53. }
54. }
Example A.106 FileLoader.java
1. import java.io.File;
2. import java.io.FileInputStream;
3. import java.io.FileOutputStream;
4. import java.io.IOException;
5. import java.io.ObjectInputStream;
6. import java.io.ObjectOutputStream;
7. import java.io.Serializable;
8. public class FileLoader{
9. public static Object loadData(File inputFile){
10. Object returnValue = null;
11. try{
12. if (inputFile.exists()){
13. if (inputFile.isFile()){
14. ObjectInputStream readIn = new ObjectInputStream(new
FileInputStream(inputFile));
15. returnValue = readIn.readObject();
16. readIn.close();
17. }
18. else {
19. System.err.println(inputFile + " is a directory.");
20. }
21. }
Search WWH ::




Custom Search