1. 程式人生 > >Java例子 Transient 關鍵字

Java例子 Transient 關鍵字

import java.io.*;

public class Demo
{
public static void main(String [] args) throws Exception
{
save();

Person p2 = read();

System.out.println(p2);
}

public static void save() throws Exception
{
Person liujie = new Person();
liujie.age=29;
liujie.name="LiuJie";

FileOutputStream fos = new FileOutputStream("D:\\person.out");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(liujie);
oos.flush();
oos.close();
}

public static Person read() throws Exception
{
FileInputStream fis = new FileInputStream("D:\\person.out");
ObjectInputStream ois = new ObjectInputStream(fis);
Person p = (Person)ois.readObject();
ois.close();
return p;
}
}

class Person implements Serializable
{
public transient int age;
public String name;

@Override
public String toString()
{
return "Person:"+"age="+age+",name="+name;
}
}