首页 > 其他 > 详细

封装通用序列化类

时间:2018-10-12 15:41:38      阅读:180      评论:0      收藏:0      [点我收藏+]


import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

import static com.alibaba.druid.util.JdbcUtils.close;

/**
* @author: wsj
* @date: 2018/10/10
* @time: 17:46
*/
@Slf4j
public class ListTranscoder {
public static <T> byte[] serialize(List<T> value) {
if (value == null) {
throw new NullPointerException("Can‘t serialize null");
}
byte[] rv = null;
ByteArrayOutputStream bos = null;
ObjectOutputStream os = null;
try {
bos = new ByteArrayOutputStream();
os = new ObjectOutputStream(bos);
for (T user : value) {
os.writeObject(user);
}
os.writeObject(null);
os.close();
bos.close();
rv = bos.toByteArray();
} catch (IOException e) {
throw new IllegalArgumentException("Non-serializable object", e);
} finally {
close(os);
close(bos);
}
return rv;
}


public static <T> List deserialize(byte[] in) {
List<T> list = new ArrayList<>();
ByteArrayInputStream bis = null;
ObjectInputStream is = null;
try {
if(in != null) {
bis=new ByteArrayInputStream(in);
is=new ObjectInputStream(bis);
while (true) {
T user = (T) is.readObject();
if(user == null){
break;
}else{
list.add(user);
}
}
is.close();
bis.close();
}
} catch (IOException e) {
log.warn("Caught IOException decoding %d bytes of data",
in == null ? 0 : in.length, e);
} catch (ClassNotFoundException e) {
log.warn("Caught CNFE decoding %d bytes of data",
in == null ? 0 : in.length, e);
} finally {
close(is);
close(bis);
}
return list;
}

}

封装通用序列化类

原文:https://www.cnblogs.com/wsjun/p/9778101.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!