按楼主贴的代码,测试了一下,是没有问题的:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class TestSeriales {
public static void main(String[] args) {
Date d1 = new Date();
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Date d2 = new Date();
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Date d3 = new Date();
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Date d4 = new Date();
HostComputer h1 = new HostComputer(d1,d2);
HostComputer h2 = new HostComputer(d3,d4);
List<Object> list = new ArrayList<Object>();
list.add(h1);
list.add(h2);
try {
byte[] bytes = serializeList(list);
System.out.println("after deseriable result is:");
List<Object> list2 = (List<Object>) descri(bytes);
for(Object o:list2) {
System.out.println(o);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 序列化 list 集合
*
* @param list
* @return
* @throws IOException
*/
public static byte[] serializeList(List<?> list) throws IOException {
if (list == null || list.size() == 0) {
return null;
}
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
byte[] bytes = null;
try {
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
for (Object obj : list) {
oos.writeObject(obj);
}
bytes = baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
} finally {
oos.close();
baos.close();
}
return bytes;
}
public static List<?> descri(byte[] bytes) throws IOException {
// 反序列化代码
if (bytes == null) {
return null;
}
List<Object> list = new ArrayList<Object>();
ByteArrayInputStream bais = null;
ObjectInputStream ois = null;
try {
// 反序列化
bais = new ByteArrayInputStream(bytes);
ois = new ObjectInputStream(bais);
while (bais.available() > 0) {
Object obj = (Object) ois.readObject();
if (obj == null) {
break;
}
list.add(obj);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
ois.close();
bais.close();
}
return list;
}
}
HostComputer 定义为:
import java.io.Serializable;
import java.util.Date;
public class HostComputer implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Date startTime;
private Date endTime;
public HostComputer(Date startTime,Date endTime) {
this.startTime = startTime;
this.endTime = endTime;
}
@Override
public String toString() {
return "HostComputer [startTime=" + startTime + ", endTime=" + endTime + "]";
}
}
测试结果:
after deseriable result is:
HostComputer [startTime=Fri Jan 03 09:13:25 CST 2020, endTime=Fri Jan 03 09:13:26 CST 2020]
HostComputer [startTime=Fri Jan 03 09:13:27 CST 2020, endTime=Fri Jan 03 09:13:28 CST 2020]
楼主可以对照您的实现对比一下,看看什么地方的问题。