标签:
import java.util.Date; public class LoggingInfo implements java.io.Serializable { private Date loggingDate = new Date(); private String uid; private transient String pwd; LoggingInfo(String user, String password) { uid = user; pwd = password; } public String toString() { String password=null; if(pwd == null) { password = "NOT SET"; } else { password = pwd; } return"logon info: \n " + "user: " + uid + "\n logging date : " + loggingDate.toString() + "\n password: " + password; } }
现在我们创建一个这个类的实例,并且串行化(serialize)它 ,然后将这个串行化对象写如磁盘。
package com.wms.test; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class TestTransient implements java.io.Serializable { public static void main(String[] args) { LoggingInfo logInfo = new LoggingInfo("MIKE", "MECHANICS"); System.out.println(logInfo.toString()); try { ObjectOutputStream o = new ObjectOutputStream( new FileOutputStream("logInfo.out")); o.writeObject(logInfo); o.close(); } catch(Exception e) { //deal with exception } //To read the object back, we can write try { ObjectInputStream in =new ObjectInputStream( new FileInputStream("logInfo.out")); LoggingInfo logInfoIn = (LoggingInfo)in.readObject(); System.out.println(logInfoIn.toString()); } catch(Exception e) { //deal with exception } } }
logon info: user: MIKE logging date : Wed Apr 13 22:13:44 CST 2016 password: MECHANICS logon info: user: MIKE logging date : Wed Apr 13 22:13:44 CST 2016 password: NOT SET
public class GuestLoggingInfo implements java.io.Serializable { private Date loggingDate = new Date(); private String uid; private transient String pwd; GuestLoggingInfo() { uid = "guest"; pwd = "guest"; } public String toString() { // same as above } }
标签:
原文地址:http://www.cnblogs.com/wangmingshun/p/5389042.html