자바(deprecated)/io
serialization
by monkey-k777
2019. 6. 10.
package demo.serialization;
import java.io.Serializable;
public class Employee implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
*
*/
private String name;
private String position;
// 직렬화, 역직렬화 대상에서 제외된다.
private transient int password;
private Family child;
public Employee() {}
public Employee(String name, String position, int password, Family child) {
super();
this.name = name;
this.position = position;
this.password = password;
this.child = child;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public int getPassword() {
return password;
}
public void setPassword(int password) {
this.password = password;
}
public Family getChild() {
return child;
}
public void setChild(Family child) {
this.child = child;
}
}
package demo.serialization;
import java.io.Serializable;
public class Family implements Serializable {
private String name;
private int count;
public Family() {}
public Family(String name, int count) {
this.name = name;
this.count = count;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
package demo.serialization;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
public class SerializationDemo1 {
public static void main(String[] args) throws Exception {
Family f = new Family("자녀", 2);
Employee employee = new Employee();
employee.setName("홍길동");
employee.setPosition("과장");
employee.setPassword(1234);
employee.setChild(f);
FileOutputStream fos = new FileOutputStream("c:/temp/emp.sav");
ObjectOutputStream oos = new ObjectOutputStream(fos);
// void writeObject(Object o)
// 객체를 직렬화한다.
oos.writeObject(employee);
oos.close();
}
}
package demo.serialization;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class DeserializationDemo1 {
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("c:/temp/emp.sav");
ObjectInputStream ois = new ObjectInputStream(fis);
// Object readObject()
// 스트림으로 읽어들인 데이터를 이용해서 객체를 복원(역직렬화)한다.
Object obj = ois.readObject();
// System.out.println(obj);
Employee emp = (Employee) obj;
System.out.println("이름 : " + emp.getName());
System.out.println("직위 : " + emp.getPosition());
System.out.println("비번 : " + emp.getPassword());
System.out.println("가족 : " + emp.getChild().getName());
System.out.println("가족수 : " + emp.getChild().getCount());
ois.close();
}
}