Java串行化与反串行化

1.串行化对象

import java.io.Serializable; /* * time:2008-07-19 * author:coke */ /* *必须实现Serializable */ public class Person implements Serializable { private static final long serialVersionUID = 1L; private int age; // will persist private String name; // will persist // transient 为Java保留字,告诉JVM以transient宣告的基本型态(primitive type)或物 // 件(object)变量不要序列化,例如敏感性数据像是密码等。 private transient String pwd; // will not persist public Person() { } public Person(int age, String name,String pwd) { this.age = age; this.name = name; this.pwd=pwd; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } }  

2.串行化和反串行化

import java.io.FileNotFoundException; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.File; /* * time:2008-07-19 * author:coke */ public class TestSerializable { private static File f = null; //串行化 public static void serialization() { f = new File("D://t.m"); try { if (f.exists()) f.delete(); f.createNewFile(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } Person p = new Person(10, "xplq", "123456"); try { ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream(f)); out.writeObject(p); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } //反串行化 public static void deserialization() { if (!f.exists()) return; try { ObjectInputStream input = new ObjectInputStream( new FileInputStream(f.getPath())); try { Person p = (Person) input.readObject(); System.out.println(p.getName()); System.out.println(p.getAge()); System.out.println(p.getPwd()); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //测试 public static void main(String[] args) { TestSerializable.serialization(); TestSerializable.deserialization(); } }  

3.测试结果 
xplq 
10 
null 
因为pwd transient ,不能被串行化 

 

 

你可能感兴趣的:(JAVA,通讯技术,IO,java,import,string,serialization,primitive,class)