Serializable序列化(二)

来源:互联网 发布:淘宝怎么引流量 编辑:程序博客网 时间:2024/05/23 02:05
package serializ;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;import java.util.Calendar;import java.util.Date;/** * 有些域不想序列化或者有些域序列化之后并没有意义 * 因为可能反序列化之后的环境:用不上有这些域,或者也不能用 *  * 使用 transient 来修饰域即可防止该字段序列化 *  * @author yli * */public class SerialTest { public static void main(String[] args) {  Page p = new Page(1001, "index", Calendar.getInstance().getTime());  System.out.println(p);  String file = "src/serializ/page.dat";  writeObject(p, file);  Page sp = (Page) readObject(file);  System.out.println(sp); } // 序列化对象 private static void writeObject(Object obj, String file) {  ObjectOutputStream oos = null;  try {   oos = new ObjectOutputStream(new BufferedOutputStream(     new FileOutputStream(file)));   oos.writeObject(obj);  } catch (FileNotFoundException e) {   e.printStackTrace();  } catch (IOException e) {   e.printStackTrace();  } finally {   try {    oos.close();   } catch (IOException e) {    e.printStackTrace();   }  } } // 反序列化 private static Object readObject(String file) {  ObjectInputStream ois = null;  Object obj = null;  try {   ois = new ObjectInputStream(new BufferedInputStream(     new FileInputStream(file)));   obj = ois.readObject();  } catch (FileNotFoundException e) {   e.printStackTrace();  } catch (IOException e) {   e.printStackTrace();  } catch (ClassNotFoundException e) {   e.printStackTrace();  } finally {   try {    ois.close();   } catch (IOException e) {    e.printStackTrace();   }  }  return obj; }}class Page implements Serializable { private static final long serialVersionUID = -5281143296574186232L; private int pageId; private String pageName;  // transient 修饰符 private transient Date createDate; public Page(int pageId, String pageName, Date createDate) {  this.pageId = pageId;  this.pageName = pageName;  this.createDate = createDate; } public String toString() {  return String.format("{pageId:%s,pageName:%s,createDate:%s}",    this.pageId, this.pageName, this.createDate); }}


 

0 0
原创粉丝点击