package File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import java.io.Serializable;import java.io.IOException;public class SerializeTest { public static void main(String[] args) { try (ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream("transient.txt")); ObjectInputStream ois = new ObjectInputStream( new FileInputStream("transient.txt"))) { Person per = new Person("孙悟空", 500); oos.writeObject(per); Person p = (Person) ois.readObject(); System.out.println(p.getName());//输出空悟孙 System.out.println(p.getAge());//输出501 } catch (Exception e) { e.printStackTrace(); } }}class Person implements Serializable { //序列化的类必须实现Serializable或Externalizable接口 private String name; private transient int age;//transient表示不进行不序列化 public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return this.name; } public int getAge() { return this.age; } public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } /*进行自定义序列化,要在序列化的类中添加两个方法,都是private,这里用到了反射*/ private void writeObject(ObjectOutputStream out)throws IOException { out.writeObject(new StringBuffer(name).reverse()); out.writeInt(age); } private void readObject(ObjectInputStream in)throws IOException, ClassNotFoundException { this.name = ((StringBuffer)in.readObject()).toString(); this.age = in.readInt()+1; }}