import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.nio.ByteBuffer; import org.apache.log4j.Logger; /** * <b>Summary: </b> * 对象与流的相互转换 * <b>Remarks: </b> * 对象与流的相互转换 */ publicclass ObjectStream { privatefinalstatic Logger log = Logger.getLogger(ObjectStream.class); /** * <b>Summary: </b> * toByteBuffer(对象转 byte 数组) * @param object * @return */ publicstaticbyte[] toByteBuffer(Object object) { ByteArrayOutputStream bio =new ByteArrayOutputStream(); ObjectOutputStream oos = null; ByteBuffer outBuf = null; try { oos =new ObjectOutputStream(bio); oos.writeObject(object); byte[] ba = bio.toByteArray(); int len = ba.length; outBuf = ByteBuffer.allocate(len); outBuf.put(ba); outBuf.flip(); } catch (IOException e) { log.error("对象序列化异常[IOException]:"+e.getMessage()); e.printStackTrace(); } finally { try { if (bio != null) bio.close(); if (oos != null) oos.close(); } catch (IOException e) { log.error("对象序列化,关闭流异常[IOException]:"+e.getMessage()); e.printStackTrace(); } } return outBuf.array(); } /** * <b>Summary: </b> * toObject(byte 数组转对象) * @param buff * @return */ publicstatic Object toObject(byte[] buff) { ByteArrayInputStream bis =new ByteArrayInputStream(buff); ObjectInputStream ois = null; Object object = null; try { ois =new ObjectInputStream(bis); object = ois.readObject(); } catch (IOException e) { log.error("对象反序列化异常[IOException]:"+e.getMessage()); e.printStackTrace(); } catch (ClassNotFoundException e) { log.error("对象反序列化异常[ClassNotFoundException]:"+e.getMessage()); e.printStackTrace(); } finally { try { if (bis != null) bis.close(); if (ois != null) ois.close(); } catch (IOException e) { log.error("对象反序列化,关闭流异常[IOException]:"+e.getMessage()); e.printStackTrace(); } } return object; } }
Java对象序列化 与 反序列化
猜你喜欢
转载自superyang0804.iteye.com/blog/2221639
今日推荐
周排行