JDK6.0学习笔记(十四)对象序列化
来源:互联网 发布:中国snapchat类似软件 编辑:程序博客网 时间:2024/05/01 18:53
- import java.io.ObjectInputStream;
- import java.io.ObjectOutputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- public class TestSerializable {
- public static void main(String[] args) throws IOException,
- ClassNotFoundException {
- File myObjectFile = new File("myobject");
- ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
- myObjectFile));
- MyObject myObject = new MyObject(0, "Tom");
- oos.writeObject(myObject);
- oos.close();
- ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
- myObjectFile));
- MyObject myObject1 = (MyObject) ois.readObject();
- System.out.println("no=" + myObject1.getNo() + ";name="+ myObject1.getName());
- ois.close();
- }
}
- import java.io.Serializable;
- import java.io.ObjectInputStream;
- import java.io.ObjectOutputStream;
- import java.io.IOException;
- public class MyObject implements Serializable {
- private int no = 0;
- transient private String name = null;
- public MyObject(int no, String name) {
- this.no = no;
- this.name = name;
- }
- public void setNo(int no) {
- this.no = no;
- }
- public int getNo() {
- return this.no;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getName() {
- return this.name;
- }
- private void writeObject(ObjectOutputStream out) throws IOException {
- out.defaultWriteObject();
- out.writeObject(this.name);
- }
- private void readObject(ObjectInputStream in) throws IOException,
- ClassNotFoundException {
- in.defaultReadObject();
- this.name = (String) in.readObject() + "...";
- }
- }