JAva-シーケンス化と逆シーケンス化
2605 ワード
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class ObjectStreamDemo {
public static void main(String[] args) {
/**
*
* ObjectOutputStream ObjectInputStream
* , java , 。
* ObjectOutputStream ;ObjectInputStream
* 。ObjectOutputStream ObjectInputStream static
* transient 。
* , java.io.Serializable 。
*/
new ObjectStreamDemo().serializationTest("e:/pratice.html");
new ObjectStreamDemo().deserializationTest("e:/pratice.html");
/**
* serialVersionUID :
* 1. , , serialVersionUID.
* 2. , , serialVersionUID.
*/
}
private void serializationTest(String filepath){
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream(filepath));
oos.writeObject(new Student(1, "xiex", 18));
oos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(oos != null){
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void deserializationTest(String filepath){
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filepath));
Student stu = (Student) ois.readObject();
System.out.println(stu);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
class Student implements Serializable{
private static final long serialVersionUID = 1L;
private int id;
private String name;
private transient int age;
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
}
public Student(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public Student() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
}