안녕하세요 케이치입니다.
오늘은 자바 객체를 바이트 배열로 변환하는 방법에 대해서 포스팅합니다.
1. Object to byte[]
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = null;
try {
out = new ObjectOutputStream(bos);
out.writeObject(yourObject);
byte[] yourBytes = bos.toByteArray();
...
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException ex) {
// ignore close exception
}
try {
bos.close();
} catch (IOException ex) {
// ignore close exception
}
}
2. byte[] to Object
ByteArrayInputStream bis = new ByteArrayInputStream(yourBytes);
ObjectInput in = null;
try {
in = new ObjectInputStream(bis);
Object o = in.readObject();
...
} finally {
try {
bis.close();
} catch (IOException ex) {
// ignore close exception
}
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
// ignore close exception
}
}
기본적인 자바를 이용하면 저렇게 하시면 되는데 아파치 유틸을 이용하면 좀 더 편하게 할 수 있습니다.
ApacheUtils 라이브러리를 다운 받아서 사용하시면 됩니다.
To Serialize:
byte[] data = SerializationUtils.serialize(yourObject);
To Deserialize:
YourObject yourObject = (YourObject) SerializationUtils.deserialize(byte[] data)
[Java/자바] 텍스트 파일 내용 읽어서 출력하기 (0) | 2016.12.04 |
---|---|
프로젝트 현재 경로 얻기 ( Getting current working directory ) (0) | 2016.06.15 |
JVM 클래스로더란? ( What is ClassLoader ? ) (0) | 2015.06.18 |
[ Java / 자바 ] 시스템 독립적인 라인 구분자 (0) | 2015.04.27 |
[ Java / 자바 ] 현재 날짜 및 시간 구하기 (0) | 2015.04.27 |