序列化的几种方式

xiaoxiao2021-02-27  350

方式一:java内置的序列化方式: ByteArrayOutputStream os=new ByteArrayOutputStream(); try { ObjectOutputStream out=new ObjectOutputStream(os); out.writeObject(student); byte[] studentByte=os.toByteArray(); ByteArrayInputStream is=new ByteArrayInputStream(studentByte); ObjectInputStream in=new ObjectInputStream(is); try { Student reStudent=(Student) in.readObject(); System.out.println(reStudent.getName()); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } 方式二:基于hessian的序列化方式,比内置的效率更高 三:将内置的序列化写成工具类: public class SerializeUtils { private static Logger logger = LoggerFactory.getLogger(SerializeUtils.class); public static void main(String[] args) { Student student=new Student(); student.setAge(1); student.setName("zm"); student.setId("id1"); byte[] bytes=serialize(student); Student dStudent=deserialize(bytes); System.out.println(dStudent.getName()); } /** * 反序列化 * * @param bytes * @return */ @SuppressWarnings("unchecked") public static <T> T deserialize(byte[] bytes) { Object result = null; if (isEmpty(bytes)) { return null; } try{ ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes); try{ ObjectInputStream objectInputStream = new ObjectInputStream(byteStream); try { result = objectInputStream.readObject(); } catch (ClassNotFoundException ex) { throw new Exception("Failed to deserialize object type", ex); } } catch (Throwable ex) { throw new Exception("Failed to deserialize", ex); } } catch (Exception e) { logger.error("Failed to deserialize ,cause by:"+e.getMessage()); } return (T) result; } public static boolean isEmpty(byte[] data) { return (data == null || data.length == 0); } /** * 序列化 * * @param object * @return */ public static byte[] serialize(Object object) { long start = System.currentTimeMillis(); byte[] result = null; if (object == null) { return new byte[0]; } try { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(128); try { if (!(object instanceof Serializable)) { throw new IllegalArgumentException(SerializeUtils.class.getSimpleName() + " requires a Serializable payload " + "but received an object of type [" + object.getClass().getName() + "]"); } ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteStream); objectOutputStream.writeObject(object); objectOutputStream.flush(); result = byteStream.toByteArray(); } catch (Throwable ex) { throw new Exception("Failed to serialize", ex); } } catch (Exception ex) { logger.warn("Failed to serialize,cause by:"+ex.getMessage()); } if (logger.isDebugEnabled()) { logger.debug("serialize object time is:" + (System.currentTimeMillis() - start)); } return result; } }
转载请注明原文地址: https://www.6miu.com/read-4173.html

最新回复(0)