직렬화는 어디에 써먹는 녀석인가?
쉽게 생각하면 IO가 발생하는 부분에 쓰는거다
Data를 주고 받는데 Object를 분해한 뒤 일열로 정렬 시켜서 사용한다는 이야기
사용법은 간단하다
송수신용 Object를 java.io.Serializable로 상속받아서 구현하면 된다
이렇게
public class SerialObj implements Serializable {
private int no;
private String title;
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
테스트는?
파일에 Object를 저장하고 다시 그 파일에서 Object를 읽어와서 출력해보기
그리고 파일을 에디터로 열어보면 이상한 글씨들과 함께 한줄로 값이 저장되어 있는 걸 확인 할 수 있을 것이다
String path_file = "d:\\test\\test.data";
File f = new File(path_file);
if(f.exists()){
f.delete();
}
FileOutputStream fileout = new FileOutputStream(path_file);
ObjectOutputStream objout = new ObjectOutputStream(fileout);
SerialObj obj = new SerialObj();
obj.setNo(1);
obj.setTitle("test1");
objout.writeObject(obj);
objout.close();
fileout.close();
FileInputStream filein = new FileInputStream(path_file);
ObjectInputStream objin = new ObjectInputStream(filein);
SerialObj readObj = (SerialObj)objin.readObject();
System.out.println(String.format("[read no] : %d", readObj.getNo()));
System.out.println(String.format("[read title] : %s", readObj.getTitle()));
objin.close();
filein.close();
'프로그램 > Java' 카테고리의 다른 글
java 랜덤 범위 지정 (0) | 2014.10.24 |
---|---|
spring cross-domain filter (0) | 2014.07.22 |
json between object (codehaus.jackson) (0) | 2014.01.09 |
자바 모니터링 툴 visualVM visualGC (0) | 2013.09.24 |
android adb shell (0) | 2012.11.02 |