java序列化备份及还原
今天工作遇到一个要把查询结果的List序列化保存到本地机,再上传到另外一个应用还原出原来的List再处理的功能.序列化:在action里面
List list = maccount.getMonthLists(cno, startdate, enddate);String filename = "test.obj"if(list!=null && !list.isEmpty()){ try{ String filename=URLEncoder.encode(filename,"UTF-8"); response.setContentType("application/x-download"); //filename应该是编码后的(utf-8) response.addHeader("Content-Disposition", "attachment; filename=" + filename); //此类实现了一个输出流,其中的数据被写入一个字节数组。缓冲区会随着数据的不断写入而自动增长 ByteArrayOutputStream baos=new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); //此类将对像写入字节流 Iterator item=list.iterator(); while(item.hasNext()){ Object obj=item.next(); oos.writeObject(obj); } byte[] data = baos.toByteArray();//獲取對像的序列化數據 OutputStream os = response.getOutputStream(); os.write(data); os.flush(); os.close(); }catch(Exception se){ log.debug(">>>>>>导出序列化对帐列表出错!"); se.printStackTrace(); }} 上面的代码实现在页面下载一个"test.obj"的文件.
上传"test.obj"文件还原List:
FormFile ff = frm.getUploadFile();try{ InputStream in = ff.getInputStream(); ObjectInputStream s = new ObjectInputStream(in); boolean re=true;//是否结束读取 while(re){ try{ Object obj = (Object)s.readObject(); list.add(obj); }catch(EOFException eofe){log.debug("Throws EOFException 还原序列化文件时已经读到文件结束符!");re=false; }catch(Exception e){log.debug("IOException1");re=false;e.printStackTrace(); } } in.close(); s.close();}catch(IOException ioe){ log.debug("IOException2"); ioe.printStackTrace();} 上面的代码把"test.obj"还原成list对象,有一个要注意的地方是Object obj = (Object)s.readObject();
方法会抛出一个EOFException 但是不影响程序继续运行.查了一些资料说EOFException 是表示已经读到文件或流的结束符但是读取对象(ObjectInputStream )还没有结束读取动作.
大家还有更好的处理方式吗?另外有什么办法避免抛出EOFException ?请大家分享一下!
页:
[1]