码迷,mamicode.com
首页 > 其他好文 > 详细

封装通用序列化类

时间:2018-10-12 16:15:33      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:druid   new   data   obj   lis   can   input   alibaba   you   



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;
}

}

封装通用序列化类

标签:druid   new   data   obj   lis   can   input   alibaba   you   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!