All Downloads are FREE. Search and download functionalities are using the official Maven repository.

top.doudou.common.tool.utils.ByteUtil Maven / Gradle / Ivy

There is a newer version: 1.3.2
Show newest version
package top.doudou.common.tool.utils;

import lombok.extern.slf4j.Slf4j;
import top.doudou.base.exception.ExceptionUtils;
import top.doudou.base.stream.StreamCloseUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @Description byte数组工具类
 * @Author 傻男人 <[email protected]>
 * @Date 2020-10-21 16:19
 * @Version V1.0
 */
@Slf4j
public class ByteUtil {

    /**
     * 二进制转十六进制
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuilder hexStr = new StringBuilder();
        int num;
        for (byte aByte : bytes) {
            num = aByte;
            if (num < 0) {
                num += 256;
            }
            if (num < 16) {
                hexStr.append("0");
            }
            hexStr.append(Integer.toHexString(num));
        }
        return hexStr.toString().toUpperCase();
    }

    /**
     * Object对象转byte[]
     */
    public static byte[] objectToByte(Object obj) {
        byte[] bytes = null;
        ByteArrayOutputStream bo = null;
        ObjectOutputStream oo = null;
        try {
            bo = new ByteArrayOutputStream();
            oo = new ObjectOutputStream(bo);
            //开始写入输出流
            oo.writeObject(obj);
            //输出流转byte
            bytes = bo.toByteArray();
        } catch (Exception e) {
            //输出到日志文件中
            log.error(ExceptionUtils.toString(e));
        } finally {
            StreamCloseUtils.close(bo);
            StreamCloseUtils.close(oo);
        }
        return bytes;
    }

    /**
     * byte[]转Object对象
     */
    public static Object byteToObject(byte[] bytes) {
        Object obj = null;
        ByteArrayInputStream bi = null;
        ObjectInputStream oi = null;
        try {
            bi = new ByteArrayInputStream(bytes);
            oi = new ObjectInputStream(bi);
            //读取输入流
            obj = oi.readObject();
        } catch (Exception e) {
            //输出到日志文件中
            log.error(ExceptionUtils.toString(e));
        } finally {
            StreamCloseUtils.close(bi);
            StreamCloseUtils.close(oi);
        }
        return obj;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy