JAVA对象和字节数组互转

JAVA对象和字节数组互转

0x01 创建要转换的类和主函数

注意这里一定要实现序列化

package day1;

import java.io.Serializable;

public class Test360 implements Serializable {
        @Override
        public String toString() {
                return "Test360{" +
                        "name='" + name + '\'' +
                        '}';
        }

        String name="test";
}


0x02 对象和字节数组互转

package day1;

import sun.jvm.hotspot.utilities.Assert;

import java.io.*;

public class arreytobytes   {
    public static void main(String[] args) throws Exception {
        Test360 test =new Test360();
        System.out.print ( "java class对象转字节数组\n" );
        byte[] bufobject = getBytesFromObject(test);
        for(int i=0 ; i<bufobject.length ; i++) {
            System.out.print(bufobject[i] + ",");
        }
        System.out.println ("\n");
        System.out.print ("字节数组还原对象\n");
        Object object1 = null;
        object1=deserialize(bufobject);
        Test360 t1 =(Test360)object1;
        System.out.println (t1.name);
    }
    public static byte[] getBytesFromObject(Serializable obj) throws Exception {
        if (obj == null) {
            return null;
        }
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bo);
        oos.writeObject(obj);
        return bo.toByteArray();
    }
    public static Object deserialize(byte[] bytes) {
        Object object = null;
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(bytes);//
            ObjectInputStream ois = new ObjectInputStream(bis);
                object = ois.readObject();
            ois.close();
            bis.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        return object;
    }
}

运行结果

java class对象转字节数组
-84,-19,0,5,115,114,0,12,100,97,121,49,46,84,101,115,116,51,54,48,76,-69,81,12,-51,122,126,-123,2,0,0,120,112,

字节数组还原对象
test

猜你喜欢

转载自blog.csdn.net/qq_38376348/article/details/107021408