Serializable를 찾아보다가 아예 예제로 연습해본다.
직렬화를 하는 이유는 java 객체를 JVM에서 꺼내서 파일과 같은 형태로 저장할 수 있는 것을 의미한다. 즉 Byte로 저장한 것을 다른 시스템에서도 가져와서 쓸 수 있게 만드는 것이다.
근데 Byte로 변환하게 되면 영속화랑 다를까? 라는 생각이 들었다.
자세히 보니 직렬화는 바이트 스트림으로 변화하는 과정이고 , 영속화는 장기적으로 보존하는 것을 의미했다.
경우에 따라서는 직렬화 한 후 파일로 저장한다. 아래는 예제이다.
우선 Person이라는 클래스를 하나 만들고 역직렬화를 해봤다.
public class Person implements Serializable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return getName();
}
public int getAge() {
return age;
}
Person person = new Person("jung", 29);
try {
// 직렬화 후 파일에 저장
FileOutputStream fileOut = new FileOutputStream("person");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(person);
out.close();
fileOut.close();
// 파일 저장 위치 체크
File file = new File("person");
System.out.println("파일 저장 위치" + file.getAbsolutePath());
} catch (IOException e) {
throw new RuntimeException(e);
}
이렇게 작성해보니 실제 파일 위치는 프로젝트 위치로 나왔다.
파일 저장 위치/Users/kimjeong-yeon/Desktop/study/JAVA/Serializable/person
만약에 이걸 다시 역직렬화 한다면 내가 원하는 결과인 jung와 29를 볼 수 있었다.
Person serializedPerson = null;
try{
FileInputStream fileInput = new FileInputStream("person");
ObjectInputStream in = new ObjectInputStream(fileInput);
serializedPerson = (Person) in.readObject();
in.close();
fileInput.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
if(serializedPerson != null){
System.out.println(serializedPerson.getName());
System.out.println(serializedPerson.getAge());
}
코드에서 readObject 메서드는 직렬화된 객체를 역직렬화한 후 객체의 복사본을 생성하는 것이다. 반환 타입이 Object이므로 원래의 객체타입인 (Person)으로 캐스팅한것이다.
직렬화 끝!