读取对象的字节数组转化为String,当String再转化字节数组时,无法还原Java对象的坑
网上的都没用,后来自己尝试解决了
写入对象
ByteArrayOutputStream out = new ByteArrayOutputStream();ObjectOutputStream sOut;try {sOut = new ObjectOutputStream(out);sOut.writeObject(obj);sOut.flush();bytes = out.toByteArray();
然后读取对象
T t = null;ByteArrayInputStream in = new ByteArrayInputStream(bytes);ObjectInputStream sIn;try {sIn = new ObjectInputStream(in);t = (T) sIn.readObject();} catch (Exception e) {e.printStackTrace();}
看起来没问题,但是当对象呗反序列化的时候却是不是行的,会有一个类似 java.io.StreamCorruptedException: invalid stream header: EFBFBDEF的异常
解决方法,对字节数组转换的时候指定16进制,在得到String时也使用相同的进制得到字节表示,这样就能确保序列化和反序列能还原对象
如转化为16进制字符串
/*** 字节数组转成16进制表示格式的字符串** @param byteArray 需要转换的字节数组* @return 16进制表示格式的字符串**/public static String toHexString(byte[] byteArray) {if (byteArray == null || byteArray.length < 1)throw new IllegalArgumentException("this byteArray must not be null or empty");final StringBuilder hexString = new StringBuilder();for (int i = 0; i < byteArray.length; i++) {if ((byteArray[i] & 0xff) < 0x10)//0~F前面不零hexString.append("0");hexString.append(Integer.toHexString(0xFF & byteArray[i]));}return hexString.toString().toLowerCase();}
在得到String的时候进行反转
public static byte[] toByteArray(String hexString) {if (StringUtils.isEmpty(hexString))throw new IllegalArgumentException("this hexString must not be empty");hexString = hexString.toLowerCase();final byte[] byteArray = new byte[hexString.length() / 2];int k = 0;for (int i = 0; i < byteArray.length; i++) {//因为是16进制,最多只会占用4位,转换成字节需要两个16进制的字符,高位在先byte high = (byte) (Character.digit(hexString.charAt(k), 16) & 0xff);byte low = (byte) (Character.digit(hexString.charAt(k + 1), 16) & 0xff);byteArray[i] = (byte) (high << 4 | low);k += 2;}return byteArray;}
进行反序列化时先把String转化为字节数组byte[]
ByteArrayUtils.toByteArray(s)
反序列读取对象
ByteArrayUtils.bytesToObject(ByteArrayUtils.toByteArray(s))
完整工具类代码:
package com.netease.readfileutil.util;import com.netease.readfileutil.core.impl.CoreIteratorDecorator;
import com.netease.readfileutil.core.impl.CoreIteratorImpl;
import org.springframework.util.StringUtils;import java.io.*;
import java.util.Optional;/*** @date: 2018-08-09* @author: liguobin* @description: 字节/字符串工具*/
public class ByteArrayUtils {public static <T> Optional<byte[]> objectToBytes(T obj) {byte[] bytes = null;ByteArrayOutputStream out = new ByteArrayOutputStream();ObjectOutputStream sOut;try {sOut = new ObjectOutputStream(out);sOut.writeObject(obj);sOut.flush();bytes = out.toByteArray();} catch (IOException e) {e.printStackTrace();}return Optional.ofNullable(bytes);}public static <T> Optional<T> bytesToObject(byte[] bytes) {T t = null;ByteArrayInputStream in = new ByteArrayInputStream(bytes);ObjectInputStream sIn;try {sIn = new ObjectInputStream(in);t = (T) sIn.readObject();} catch (Exception e) {e.printStackTrace();}return Optional.ofNullable(t);}public static void main(String[] args) {CoreIteratorDecorator coreIteratorDecorator = new CoreIteratorDecorator(new CoreIteratorImpl());System.out.println(coreIteratorDecorator.toString());Optional<byte[]> bytes = ByteArrayUtils.objectToBytes(coreIteratorDecorator);//将对象转换为二进制字节数组byte[] ret = bytes.get();String r1 = ByteArrayUtils.toHexString(ret);//序列化后的反序列化是新的对象byte[] r2 = ByteArrayUtils.toByteArray(r1);CoreIteratorDecorator coreIteratorDecorator1 = (CoreIteratorDecorator) ByteArrayUtils.bytesToObject(r2).get();System.out.println(coreIteratorDecorator1.toString());}public static byte[] toByteArray(String hexString) {if (StringUtils.isEmpty(hexString))throw new IllegalArgumentException("this hexString must not be empty");hexString = hexString.toLowerCase();final byte[] byteArray = new byte[hexString.length() / 2];int k = 0;for (int i = 0; i < byteArray.length; i++) {//因为是16进制,最多只会占用4位,转换成字节需要两个16进制的字符,高位在先byte high = (byte) (Character.digit(hexString.charAt(k), 16) & 0xff);byte low = (byte) (Character.digit(hexString.charAt(k + 1), 16) & 0xff);byteArray[i] = (byte) (high << 4 | low);k += 2;}return byteArray;}/*** 字节数组转成16进制表示格式的字符串** @param byteArray 需要转换的字节数组* @return 16进制表示格式的字符串**/public static String toHexString(byte[] byteArray) {if (byteArray == null || byteArray.length < 1)throw new IllegalArgumentException("this byteArray must not be null or empty");final StringBuilder hexString = new StringBuilder();for (int i = 0; i < byteArray.length; i++) {if ((byteArray[i] & 0xff) < 0x10)//0~F前面不零hexString.append("0");hexString.append(Integer.toHexString(0xFF & byteArray[i]));}return hexString.toString().toLowerCase();}
}
这样就可以在网络中以String形式传输二进制对象了。