在我们的日常生活中,我们可能需要把对象序列化存储在某个中间介质中。然后在某个时候,将对象取出来,进行反序列化。
持续补充中 。。。。
下面展示下如何实现:
被序列化与反序列的化的类需要实现 serialize 接口 :
package com.yaobaling.td.blacklist.model;
import com.yaobaling.td.blacklist.constants.duration.DurationEnum;
import java.io.Serializable;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* Created by szh on 2018/10/11.
*
* @author szh
*/
public class TimeSeq implements Serializable {
private SortedMap<Long, Integer> timeSeqListMap = new TreeMap<>();
private static final Integer INIT_VALUE = 1;
public SortedMap getTimeSeqListMap() {
return timeSeqListMap;
}
public void addAll(List<Long> collections) {
for (Long tmpTimeStamp : collections) {
if (timeSeqListMap.containsKey(tmpTimeStamp)) {
Integer oldValue = timeSeqListMap.get(tmpTimeStamp);
timeSeqListMap.put(tmpTimeStamp, ++oldValue);
} else {
timeSeqListMap.put(tmpTimeStamp, INIT_VALUE);
}
}
}
public Integer getTimeStampSize() {
Integer count = 0;
for (Long tmpTimeStamp : timeSeqListMap.keySet()) {
count += timeSeqListMap.get(tmpTimeStamp);
}
return count;
}
public void refresh() {
this.refresh(DurationEnum.ONE_HOUR.getDuration());
}
public void refresh(DurationEnum durationEnum){
this.refresh(durationEnum.getDuration());
}
public void refresh(Long durationMs) {
Long abandonTime = timeSeqListMap.lastKey() - durationMs;
timeSeqListMap = timeSeqListMap.tailMap(abandonTime);
}
}
对象序列化 :
public static byte[] timeSeqSerialize(TimeSeq timeSeq) throws Exception{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(timeSeq);
return bos.toByteArray();
}
对象反序列化 :
public static TimeSeq timeSeqDeSerialize(byte[] objArr) throws Exception{
ByteArrayInputStream bis = new ByteArrayInputStream(objArr);
ObjectInputStream ois = new ObjectInputStream(bis);
return (TimeSeq) ois.readObject();
}