본문 바로가기

[IT/Programming]/Algorithm/Database

Java Serializable Object to Byte Array (byte[] or SQL BLOB)

반응형
# Java Serializable Object to Byte Array (byte[] or SQL BLOB) MySQL 에 Java Serializable Object 를 byte[] data 로 저장해 뒀다가 필요할때마다 꺼내쓰고 싶어서 알아보는 중 . 그냥 string 형태로 변환한 뒤에 저장했다가 string 으로 읽어들이고 분석해서 처리하도록 짤수도 있긴한데... 속도면이나 프로그램 가독성 면에서 안좋을듯? ## TOC ## Using Streams Exception 처리나 close() 처리해야해서 좀 짜증나긴 하는듯. ### To byte[] ```[.scrollable.lang-java] 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 } } ```/ ### To YourObject ```[.scrollable.lang-java] 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 } } ```/ ## Using ApacheUtils org.apache.commons.lang.SerializationUtils 간단한거 같긴한데, class (.jar 파일 같은거) 를 따로 깔아야 할듯? 어디서 다운받는거지? ```[.scrollable.lang-java] import org.apache.commons.lang.SerializationUtils; // Serialize byte[] data=SerializationUtils.serialize(yourObject); // Deserialize YourObject yourObject=(YourObject)SerializationUtils.deserialize(byte[] data); ```/ ## RRA
  1. stackoverflow - Java Serializable Object to Byte Array, 2010-05-14, asked by iTEgg, answered by Taylor Leese
    // ApacheUtils 쓴다는 두번째 답변이 더 간단해 보이기는 하는데, JAVA 에서 기본적으로 제공하는 class 가 아닌듯?
  2. commons.apache.org - 2.6 API - Class org.apache.commons.lang.SerializationUtils
반응형