zoukankan      html  css  js  c++  java
  • java对象数组相互转化

    package com.csf.nio.demo1;
    
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    
    /**
     * Createy by user on 9/10/2018.10:39
     */
    public class SerializableUtil {
    
    
        /**
         * java对象序列化成字节数组
         *
         * @param object
         * @return
         */
        public static byte[] toBytes(Object object) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = null;
            try {
                oos = new ObjectOutputStream(baos);
                oos.writeObject(object);
                byte[] bytes = baos.toByteArray();
                return bytes;
            } catch (IOException ex) {
                throw new RuntimeException(ex.getMessage(), ex);
            } finally {
                try {
                    oos.close();
                } catch (Exception e) {
                }
            }
        }
    
    
        /**
         * 字节数组反序列化成java对象
         *
         * @param bytes
         * @return
         */
        public static Object toObject(byte[] bytes) {
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = null;
            try {
                ois = new ObjectInputStream(bais);
                Object object = ois.readObject();
                return object;
            } catch (IOException ex) {
                throw new RuntimeException(ex.getMessage(), ex);
            } catch (ClassNotFoundException ex) {
                throw new RuntimeException(ex.getMessage(), ex);
            } finally {
                try {
                    ois.close();
                } catch (Exception e) {
                }
            }
        }
    }
  • 相关阅读:
    ASP.NET Core 静态资源的打包与压缩
    算法
    字符串反转
    js 获取随机数
    AspNetCore MVC 跨域
    add digits
    1-bit and 2-bit Characters
    删除字符串中出现次数最少的字符
    洗牌
    哈夫曼编码
  • 原文地址:https://www.cnblogs.com/xiaolei2017/p/9682902.html
Copyright © 2011-2022 走看看