직렬화
직렬화와 역직렬화
클래스의 상태를 저장해 전송하거나 저장할 일이 있다. 그럴때 인스턴스의 어느 순간을 저장하는것을 직렬화라고 한다. (Serialization)
인스턴스의 저장된 상태를 다시 복원하는 것을 역직렬화라고 한다. (Deserialization)
직렬화란 간단하게 인스턴스의 내용을 연속 스트림으로 만드는 것이다. 스트림으로 만들어야 파일에 쓸 수도 있고 네트워크로 전송할 수도 있다.
직렬화를 위한 보조 스트림
ObjectInputStream(InputStream in)
ObjectOutputStream(OutputStream out)
직렬화/역직렬화 테스트
java 복사 class Person implements Serializable {
// private static final long serialVersionUID = -2345L;
String name;
String job;
public Person () {
}
public Person (String name, String job) {
this .name = name;
this .job = job;
}
public String toString () {
return name + ", " + job;
}
}
public class SerialTest {
public static void main (String[] args) throws ClassNotFoundException {
Person personKang = new Person ("Kang" , "CEO" );
Person personPak = new Person ("Pak" , "CTO" );
try (FileOutputStream fos = new FileOutputStream ("serial.out" );
ObjectOutputStream oos = new ObjectOutputStream (fos)) {
oos.writeObject (personKang);
oos.writeObject (personPak);
} catch (IOException e) {
e.printStackTrace ();
}
///
try (FileInputStream fis = new FileInputStream ("serial.out" );
ObjectInputStream ois = new ObjectInputStream (fis)) {
Person s1 = (Person) ois.readObject ();
Person s2 = (Person) ois.readObject ();
System.out.println (s1);
System.out.println (s2);
} catch (IOException e) {
e.printStackTrace ();
}
}
}
Serializable 인터페이스 : 직렬화를 사용하기 위해 대상 클래스를 Serializable 인터페이스로 구현해야한다.
transient 키워드 : 직렬화 하고 싶지 않은 변수나 클래스, 또는 직렬화 할 수 없는 클래스를 제외할 때 자료형 앞에 사용한다.
serialVersionUID : 객체를 직렬화나 역직렬화를 할 때 클래스의 상태가 다르면 오류가 발생한다. (클래스 수정과 같은 변경 과정 등등) 그래서 직렬화를 할 때 자동으로 serialVersionUID를 생성하여 정보를 저장한다. 이것을 비교하여 클래스 내용이 변경되었다면 버전이 맞지 않다는 오류가 발생한다.
Externalizable 인터페이스
- 개발자가 구현해야 하는 메소드가 있다.
그 외 IO클래스
File Class
파일 그 자체의 개념을 추상화한 클래스.
입출력 기능은 없으나 파일 경로 같은 정보를 알 수 있다.
File 클래스 테스트
java 복사 public class FileTest {
public static void main (String[] args) throws IOException {
File file = new File ("newFile.txt" );
file.createNewFile ();
System.out.println (file.isFile ());
System.out.println (file.isDirectory ());
System.out.println (file.getName ());
System.out.println (file.getAbsolutePath ());
System.out.println (file.getPath ());
System.out.println (file.canRead ());
System.out.println (file.canWrite ());
file.delete ();
}
}
RandomAccessFile Class
파일의 임의의 위치로 이동하여 자료를 읽을 수 있다. (파일 포인터)
파일의 입력과 출력을 동시에 할 수 있다.
파일 포인터의 위치를 잘 지정해야한다.