将good队列序列化到文件,并根据日期排序输出;
public class good implements Serializable
代码如下:
View Code
1 package com.app;
2 import java.io.FileInputStream;
3 import java.io.FileNotFoundException;
4 import java.io.FileOutputStream;
5 import java.io.IOException;
6 import java.io.ObjectInputStream;
7 import java.io.ObjectOutputStream;
8 import java.io.Serializable;
9 import java.util.ArrayList;
10 import java.util.Collections;
11 import java.util.Comparator;
12
13 public class app {
14
15 private static ArrayList<good> goodlist;
16 /**
17 * @param args
18 */
19 public app(){
20 goodlist = new ArrayList<good>();
21 }
22
23 public static void main(String[] args) {
24 // TODO Auto-generated method stub
25 ObjectOutputStream os = null;
26 good good1 = new good();
27 good1.setYear(2001);
28 good1.setMonth(11);
29 good1.setDay(2);
30 good1.setId(0);
31
32 ArrayList<good> input = new ArrayList<good>();//ArrayList中存储着对象的地址
33 input.add(good1);
34
35 good good2 = new good();
36 good2.setYear(2001);
37 good2.setMonth(10);
38 good2.setDay(2);
39 good2.setId(1);
40 input.add(good2);
41
42 good good3 = new good();
43 good3.setYear(1991);
44 good3.setMonth(10);
45 good3.setDay(12);
46 good3.setId(2);
47 input.add(good3);
48
49 try {
50 os = new ObjectOutputStream(new FileOutputStream("./good.dat"));
51 os.writeObject(input);
52 os.flush();
53 os.close();
54
55 } catch (FileNotFoundException e) {
56 // TODO Auto-generated catch block
57 e.printStackTrace();
58 } catch (IOException e) {
59 // TODO Auto-generated catch block
60 e.printStackTrace();
61 }
62
63 try {
64 ObjectInputStream ois=new ObjectInputStream(new FileInputStream("good.dat"));
65
66 //答应good列表
67 goodlist = (ArrayList<good>)ois.readObject();//序列化中读出的和写入的类型是一样,否额
68 //出现cast错误
69
70 //goodlist根据日期排序
71 Comparator<good> comparator = new Comparator<good>(){
72 public int compare(good input1, good input2){
73 if(input1.getYear() != input2.getYear()){
74 return input1.getYear() - input2.getYear();
75 }else{
76 if(input1.getMonth() != input2.getMonth()){
77 return input1.getMonth() - input2.getMonth();
78 }else{
79 return input1.getDay() - input2.getDay();
80 }
81 }
82 }
83 };
84
85 Collections.sort(goodlist, comparator);
86
87 for(int i = 0; i < goodlist.size(); i++){
88 System.out.println(goodlist.get(i).getId());
89 System.out.println(goodlist.get(i).getYear());
90 System.out.println(goodlist.get(i).getMonth());
91 System.out.println(goodlist.get(i).getDay());
92 }
93
94 } catch (FileNotFoundException e) {
95 // TODO Auto-generated catch block
96 e.printStackTrace();
97 } catch (IOException e) {
98 // TODO Auto-generated catch block
99 e.printStackTrace();
100 } catch (ClassNotFoundException e) {
101 // TODO Auto-generated catch block
102 e.printStackTrace();
103 }
104 }
105 }