如何将一个对象以序列化的方式写到文件中呢,请看下面代码:
首先创建一个类,若想该类能以序列化的方式写到流中,必须实现Serializable
import java.io.Serializable;
public class Person implements Serializable{
private String name = "";
private int age = 0;
private String phone = "";
private Clothes clothes = null;
public Person(String name, int age, String phone, Clothes clothes){
this.name = name;
this.age = age;
this.phone = phone;
this.clothes = clothes;
}
public void disString(){
System.out.println("name: " + name + "; age: " + age + "; phone: " + phone);
}
}
注意,该类中有一个Clothes对象,该类的代码实现如下:
public class Clothes {
private int id = 0;
public Clothes(int id){
this.id = id;
}
}
现在通过ObjectOutputStream将Person类的对象写到流中,再用FileOutputStream将流写到文件中:
Person person = new Person("lisi", 10, "12345678", new Clothes(11));
try {
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("person.dat"));
objectOutputStream.writeObject(person);
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("person.dat"));
Person pre = (Person)objectInputStream.readObject();
per.disString();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
运行,结果如下:
程序抛出异常,为什么呢?我们注意到,Person类中有一个成员变量是Clothes类的,但该类没有并没有实现Serializable。所以再序列化clothes成员的时候抛出异常。
解决方式:
若希望将clothes成员变量也序列化,那必须让Clothes类实现Serializable。
public class Clothes implements Serializable{
若不希望clothes成员变量也序列化,则在声明该变量的时候加上transient关键字。序列化的时候将跳过该成员:
private transient Clothes clothes = null;