1 import java.io.FileInputStream;
2 import java.io.FileNotFoundException;
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 import java.util.Date;
9
10 public class Main {
11 public static void main(String[] args) {
12 LoggingInfo logInfo = new LoggingInfo("MIKE", "MECHANICS");
13 System.out.println(logInfo.toString());
14 /*
15 * logon info:
16 * user: MIKE
17 * logging date : Mon Sep 29 09:40:29 CST 2014
18 * password: MECHANICS
19 */
20 ObjectOutputStream o;
21 try {
22 o = new ObjectOutputStream(
23 new FileOutputStream("logInfo.out"));
24 /* 将对象序列化保存到磁盘中 */
25 o.writeObject(logInfo);
26 o.close();
27 } catch (FileNotFoundException e) {
28 e.printStackTrace();
29 } catch (IOException e) {
30 e.printStackTrace();
31 }
32
33
34 ObjectInputStream in;
35 try {
36 in = new ObjectInputStream(
37 new FileInputStream("logInfo.out"));
38 LoggingInfo logInfo1;
39 try {
40 /* 从磁盘中读回对象 */
41 logInfo1 = (LoggingInfo)in.readObject();
42
43 /*
44 * 由于pwd变量没有被序列化,所以读出对象中pwd为null
45 */
46 System.out.println(logInfo1.toString());
47 } catch (ClassNotFoundException e) {
48 e.printStackTrace();
49 }
50
51 } catch (FileNotFoundException e) {
52 e.printStackTrace();
53 } catch (IOException e) {
54 e.printStackTrace();
55 }
56 /*
57 * logon info:
58 * user: MIKE
59 * logging date : Mon Sep 29 09:40:29 CST 2014
60 * password: NOT SET
61 *
62 */
63 }
64 }
65 class LoggingInfo implements Serializable{
66
67 private Date loggingDate = new Date();
68 private String uid;
69 /* 用tranisent 修饰一个变量,当类的对象被序列化时,此变量的值将不被序列化 */
70 private transient String pwd;
71
72 LoggingInfo(String uid, String pwd){
73 this.uid = uid;
74 this.pwd = pwd;
75 }
76
77 public String toString(){
78 String password=null;
79 if(pwd == null){
80 password = "NOT SET";
81 }
82 else {
83 password = pwd;
84 }
85 return "logon info: \n " + "user: " + uid +
86 "\n logging date : " + loggingDate.toString() +
87 "\n password: " + password;
88 }
89 }