Tuesday, March 26, 2019

Java: Example of convert Object to bytes and vice versa


The code of Object2Bytes.java:

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

public class Object2Bytes {
    public static byte[] object2Bytes(Object obj) {
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;

        try {
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.flush();

            return bos.toByteArray();
        } catch (IOException ex) {

        } finally {
            try {
                if (oos != null)
                    oos.close();

                if (bos != null)
                    bos.close();
            } catch (IOException ex) {

            }
        }

        return null;
    }

    public static Object bytes2Object(byte[] bt) {
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;

        try {
            bis = new ByteArrayInputStream(bt);
            ois = new ObjectInputStream(bis);

            return ois.readObject();
        } catch (IOException ex) {

        } catch (ClassNotFoundException ex) {

        } finally {
            try {
                if (ois != null)
                    ois.close();

                if (bis != null)
                    bis.close();
            } catch (IOException ex) {

            }
        }

        return null;
    }
}

The test code of Object2BytesTest.java is below. The class must implements Serializable in order to be converted into bytes.

import org.junit.Test;

import java.io.Serializable;

public class Object2BytesTest implements Serializable {
    public class SimpleClass implements Serializable {
        private int i;

        public int getI() {
            return i;
        }

        public void setI(int i) {
            this.i = i;
        }
    }

    @Test    public void test1() {
        SimpleClass sc = null;
        byte[] bt = null;

        sc = new SimpleClass();
        sc.setI(10);
        bt = Object2Bytes.object2Bytes(sc);
        sc = (SimpleClass)Object2Bytes.bytes2Object(bt);
        System.out.println(sc.getI());

        sc.setI(20);
        bt = Object2Bytes.object2Bytes(sc);
        sc = (SimpleClass)Object2Bytes.bytes2Object(bt);
        System.out.println(sc.getI());
    }
}

The output of the test:
10
20


No comments:

 
Get This <