1. 程式人生 > >對序列化和反序列化的理解

對序列化和反序列化的理解

import java.io.Serializable;

import java.io.*;

public class Cat implements Serializable {

private String name;

public Cat() {

this.name = "new cat";

}

public String getName() {

return this.name;

}

public void setName(String name) {

this.name = name;

}

public static void main(String[] args) {

Cat cat = new Cat();

try {

FileOutputStream fos = new FileOutputStream("catDemo.out"); //這就是你序列化檔案的儲存位置,是由自己控制的

ObjectOutputStream oos = new ObjectOutputStream(fos);

System.out.println(" 1> " + cat.getName());

cat.setName("My Cat");

oos.writeObject(cat);

oos.close();

}

catch (Exception ex) {

ex.printStackTrace();

}

try {

FileInputStream fis = new FileInputStream("catDemo.out");

ObjectInputStream ois = new ObjectInputStream(fis);

cat = (Cat) ois.readObject();

System.out.println(" 2> " + cat.getName());

ois.close();

}

catch (Exception ex) {

ex.printStackTrace();

}

}

}

輸出內容:

很抱歉,回答者上傳的附件已失效