java ObjectIn/OutStream的用法

不設限發表於2011-12-09

條件:

被序列化的類必須要實現Serializable介面


類:

import java.io.Serializable;

public class Employ implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Employ(String name, int age) {
super();
this.name = name;
this.age = age;
}

public void showInfo() {
System.out.println("姓名: "+this.name+"\t年齡: "+this.age);
}
}


把Object寫入檔案的方法:

public class WriteObject {
public static void main(String[] args) throws Exception {
WriteObject wo=new WriteObject();
FileOutputStream fos=new FileOutputStream("employ.obj");
ObjectOutputStream oos=new ObjectOutputStream(fos);

Employ e1=new Employ("dada", 24);
Employ e2=new Employ("dandan", 23);

oos.writeObject(e1);
oos.writeObject(e2);
oos.close();
fos.close();

}
}


把Object從檔案中讀取出來的方法


import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class ReadObject {
public static void main(String[] args) throws Exception {
File f=new File("employ.obj");
FileInputStream fis=new FileInputStream(f);
ObjectInputStream ois=new ObjectInputStream(fis);
Employ e1=(Employ) ois.readObject();
Employ e2=(Employ) ois.readObject();
e1.showInfo();
e2.showInfo();
}
}

相關文章