【发布时间】:2016-09-16 23:15:54
【问题描述】:
我想建立一个函数来序列化对象的ArrayList,另一个反序列化ArryList。也就是说,
public void serializeArrays(ArrayList<?> array,String className){
FileOutputStream fileOut= null;
ObjectOutputStream out=null;
try {
fileOut = new FileOutputStream("../Files/"+className+".ser");
out = new ObjectOutputStream(fileOut);
out.writeObject(array);
fileOut.close();
out.close();
}catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
该代码将序列化ArrayList的对象,这是否意味着Arraylist的所有对象都将被序列化,或者只有第一个对象所以我必须循环整个数组?
反序列化的问题是返回类型不能是ArrayList,因为对象不是固定类,所以我让它返回一个Object,所以我会转换返回值。这样处理好不好?
public Object deserializeArrays(String className){
try {
FileInputStream fileIn = new FileInputStream("../Files/"+className+".ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
return in.readObject();
}catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException ie) {
ie.printStackTrace();
}catch(ClassNotFoundException ce) {
System.out.println(" "+className+" class not found");
ce.printStackTrace();
}
}
该代码中的问题是我无法关闭fileIn 和in,
如果我把它放在最后,报错说:
未报告的异常IOException;必须被抓住或宣布被扔掉
而且又报错了
错误:缺少返回语句
【问题讨论】:
标签: java serialization arraylist