序列化和反序列化
ObjectInputStream 反序列化 readObject()--》類型轉換
ObjectOutputStream 序列化 writeObject(Object)
常見異常:
NotSerializableException:類沒有實作Serializable接口,不可被序列化
transient屏蔽某些敏感字段的序列化
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* 測試序列化ObjectOuputStream
* 反序列化ObjectInputStream
* @author 77309
*/
public class ObjeceInputTest {
public static void main(String[] args) {
Student stu=new Student("小強",16,"男","123456");
//序列化
ObjectOutputStream oos=null;
FileOutputStream fos=null;
//反序列化
ObjectInputStream ois=null;
FileInputStream fis=null;
try {
fos=new FileOutputStream("D:/student.txt");
oos=new ObjectOutputStream(fos);
oos.writeObject(stu);
fis=new FileInputStream("D:/student.txt");
ois=new ObjectInputStream(fis);
Student stu1=(Student)ois.readObject();
System.out.println(stu1.getName()+"-"+stu1.getAge()+"-"+stu1.getSex()+"-"+stu1.getPssdWord());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally{
try {
fis.close();
ois.close();
fos.close();
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
import java.io.Serializable;
public class Student implements Serializable {
private String name;
private int age;
private String sex;
private transient String pssdWord;
public Student(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public Student(String name, int age, String sex, String pssdWord) {
this.name = name;
this.age = age;
this.sex = sex;
this.pssdWord = pssdWord;
}
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 String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getPssdWord() {
return pssdWord;
}
public void setPssdWord(String pssdWord) {
this.pssdWord = pssdWord;
}
}