Java中 对象和二进制数组(byte array)之间的互转

直接上代码

package com.study.auth.config.core.handler;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.Arrays;
import java.util.Objects;

/**
 * @Package: com.study.auth.config.core.handler
 * @Description: <对象和二进制数组及流对象间的转换>
 * @Author: milla
 * @CreateDate: 2020/09/09 09:52
 * @UpdateUser: milla
 * @UpdateDate: 2020/09/09 09:52
 * @UpdateRemark: <>
 * @Version: 1.0
 */
@Slf4j
public class ByteArrayUtil {
    public static void main(String[] args) {
        Student student = new Student("冯程程", "上海金融大街", 23, "女");
        byte[] array = toByteArray(student);
        System.out.println("字节数组:" + Arrays.toString(array));
        ByteArrayOutputStream arrayOutputStream = toOutputStream(student);
        System.out.println("输出流: " + arrayOutputStream);

        Student obj = toObject(array, Student.class);
        Student obj1 = toObject(arrayOutputStream, Student.class);

        System.out.println("字节数组转换成对象:" + obj);
    }

    /**
     * 将ByteArrayOutputStream输出流转换成对象
     *
     * @param outputStream 输出流
     * @param clazz        要转话程的对象class文件
     * @param <T>          要转化的对象
     * @return
     */
    public static <T> T toObject(ByteArrayOutputStream outputStream, Class<T> clazz) {
        if (Objects.isNull(outputStream)) {
            log.error("outputStream array can not be null");
            return null;
        }
        byte[] data = outputStream.toByteArray();
        return toObject(data, clazz);
    }

    /**
     * 将输入流转换成对象
     *
     * @param inputStream 输入流
     * @param clazz       要转换成对象的class文件
     * @param <T>         要转换程的对象类型
     * @return
     */
    public static <T> T toObject(InputStream inputStream, Class<T> clazz) {
        if (Objects.isNull(inputStream)) {
            log.error("inputStream array can not be null");
            return null;
        }
        ObjectInputStream obj = null;
        try {
            obj = new ObjectInputStream(inputStream);
            return (T) obj.readObject();
        } catch (IOException | ClassNotFoundException e) {
            log.error("byte array to {} failed: {}", clazz.getName(), e);
            return null;
        } finally {
            try {
                if (Objects.nonNull(inputStream)) {
                    inputStream.close();
                }
                if (Objects.nonNull(obj)) {
                    obj.close();
                }
            } catch (IOException e) {
                log.error("stream close failed: {}", e);
            }

        }
    }

    /**
     * 将byte数组转换成对象
     *
     * @param array byte数组
     * @param clazz 要转成的对象字节码
     * @param <T>   要转成的类型
     * @return
     */
    public static <T> T toObject(byte[] array, Class<T> clazz) {
        if (Objects.isNull(array) || array.length == 0) {
            log.error("byte array can not be null");
            return null;
        }
        ByteArrayInputStream bis = new ByteArrayInputStream(array);
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(bis);
            return (T) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            log.error("byte array to {} failed: {}", clazz.getName(), e);
            return null;
        } finally {
            try {
                if (Objects.nonNull(bis)) {
                    bis.close();
                }
                if (Objects.nonNull(ois)) {
                    ois.close();
                }
            } catch (IOException e) {
                log.error("stream close failed: {}", e);
            }

        }
    }

    /**
     * 将对象抓换成二进制对象
     * Ps:对象必须实现Serializable接口,最好能给定一个serialVersionUID
     *
     * @param data 对象
     * @return
     */
    public static byte[] toByteArray(Object data) {
        ByteArrayOutputStream outputStream = toOutputStream(data);
        if (Objects.isNull(outputStream)) {
            return null;
        }
        return outputStream.toByteArray();
    }

    /**
     * 将对象转换成输出流
     * Ps:对象必须实现Serializable接口,最好能给定一个serialVersionUID
     *
     * @param data 对象
     * @return
     */
    public static ByteArrayOutputStream toOutputStream(Object data) {
        if (Objects.isNull(data)) {
            log.error("{} can not be null", data.getClass().getName());
            return null;
        }
        ByteArrayOutputStream array = new ByteArrayOutputStream();
        ObjectOutputStream objectWrite = null;
        try {
            objectWrite = new ObjectOutputStream(array);
            objectWrite.writeObject(data);
            objectWrite.flush();
            return array;
        } catch (IOException e) {
            log.error("{} to byte array failed: {}", data.getClass().getName(), e);
            return null;
        } finally {
            try {
                if (Objects.nonNull(array)) {
                    array.close();
                }
                if (Objects.nonNull(objectWrite)) {
                    objectWrite.close();
                }
            } catch (IOException e) {
                log.error("stream close failed: {}", e);
            }
        }
    }

}

@Data
class Student implements Serializable {
    /**
     * 序列化/反序列化必须实现Serializable接口
     * 想要不出现类型转换异常就需要有一个统一的serialVersionUID
     */
    private static final long serialVersionUID = 7824278330465676953L;

    private String name;
    private String address;
    private Integer age;
    private String sex;

    public Student(String name, String address, Integer age, String sex) {
        this.name = name;
        this.address = address;
        this.age = age;
        this.sex = sex;
    }
}

 必要的依赖

   <dependency>
       <groupId>org.projectlombok</groupId>
       <artifactId>lombok</artifactId>
       <version>1.18.12</version>
   </dependency>

 

 PS::

  1.  对象一定要实现Serializable接口,否则不具备转换的基础条件
  2. 和对象序列化一样,如果对象有修改的可能一定要定义一个唯一serialVersionUID
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 游动-白 设计师:白松林 返回首页