#자바 (1)

💻 Programming/Java

자바 객체를 byte[] 로 변환하기

안녕하세요 케이치입니다. 


오늘은 자바 객체를 바이트 배열로 변환하는 방법에 대해서 포스팅합니다.



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)
달랑 한줄로 Object -> byte[] 도 가능하고 역으로도 가능하네요.

참 간단하쥬잉~?

이상 케이치였습니다.

즐프하세요~