对象字节数组转换工具类

来源:互联网 发布:js读取div内容 编辑:程序博客网 时间:2024/04/30 23:44
package cn.tootoo.kzh.util.redis;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.Closeable;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/** *  * ClassName: ObjectsTranscoder *  * @Description: 对象字节数组转换工具类 */ class ObjectsTranscoder {private static final Logger LOGGER = LoggerFactory.getLogger(ObjectsTranscoder.class);private ObjectsTranscoder() {}private static ObjectsTranscoder objectsTranscoder;public static ObjectsTranscoder getInstance() {if (objectsTranscoder == null) {objectsTranscoder = new ObjectsTranscoder();}return objectsTranscoder;}public byte[] serialize(Object value) {if (value == null) {LOGGER.error("null value error");}byte[] result = null;ByteArrayOutputStream bos = null;ObjectOutputStream os = null;try {bos = new ByteArrayOutputStream();os = new ObjectOutputStream(bos);os.writeObject(value);os.close();bos.close();result = bos.toByteArray();} catch (IOException e) {LOGGER.error("Non-serializable object", e);} finally {close(os);close(bos);}return result;}public Object deserialize(byte[] in) {Object result = null;ByteArrayInputStream bis = null;ObjectInputStream is = null;try {if (in != null) {bis = new ByteArrayInputStream(in);is = new ObjectInputStream(bis);result = is.readObject();is.close();bis.close();}} catch (IOException e) {LOGGER.error("convert byte to Object error", e);} catch (ClassNotFoundException e) {LOGGER.error("convert byte to Object error", e);} finally {close(is);close(bis);}return result;}private static void close(Closeable closeable) {if (closeable != null) {try {closeable.close();} catch (Exception e) {LOGGER.info("Unable to close " + closeable, e);}}}}

原创粉丝点击