您的位置:首页 > 其它

对象字节数组转换工具类

2017-08-10 16:10 204 查看
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);
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐