오늘은 Serialize에 대해 글을 작성하려고 합니다.
한글로는 직렬화입니다.
class Person implements Serializable
private transient int age;
ObjectOutputSteram()
ObjectInputStream()
public class ObjectTest {
public static void main(String[] args) {
String file ="object.txt";
try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file))) {
oos.writeObject(new Employee("1","va",100000000));
Employee.salary = 5000000;
System.out.println(ois.readObject());
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class Employee implements Cloneable, Serializable{
private String empno;
private String ename;
public static int salary;
public Employee() {
}
public Employee(String empno, String ename, int salary) {
this.empno = empno;
this.ename = ename;
this.salary = salary;
}
}
결과는
object.txt는
이렇게 연속적인 데이터로 파일에 저장이 된다.
근데 이걸 꼭 직렬화를 해야할까?
어디에서 사용되고 있을까?
직렬화: JVM의 힙(heap) 혹은 스택(stack) 메모리에 상주하고 있는 객체 데이터를 직렬화를 통해 바이트 형태로 변환하여 데이터베이스나 파일과 같은 외부 저장소로 저장해둔다.
역직렬화: 다른 컴퓨터에서 이 파일을 가져와 역직렬화를 통해 자바 객체로 변환해서 JVM 메모리에 적재한다.
직렬화를 응용한다면 휘발성이 있는 캐싱 데이터를 영구 저장이 필요할 때 사용할 수 있다.
서블릿 세션(Servlet Session)
캐시(Cache)