byte[]和Object之间的互转

将Object对象转换成byte[]

public static byte[] getBytes(Object obj) {
        try {
            ByteArrayOutputStream bs = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bs);
            oos.writeObject(obj);
            byte[] buf = bs.toByteArray();
            oos.flush();
            return buf;
        }
        catch (IOException e) {
            e.printStackTrace();
            LOGGER.info("convert to byte fail");
        }
        return null;
    }

 

将byte[]转换成Object

public static Object getObject(byte[] bs) {

        try {
            ByteArrayInputStream bais = new ByteArrayInputStream(bs);
            ObjectInputStream ois = new ObjectInputStream(bais);
            return ois.readObject();
        }
        catch (IOException e) {
            LOGGER.info("convert to Object fail");
        }
        catch (ClassNotFoundException e) {
            LOGGER.info("File not found");
        }
        return null;
    }

 

你可能感兴趣的:(object)