2007-06-22

EMF序列化注意事项

关键字: EMF 序列化 恢复
在对EMF模型保存成xml文件的时候,有时候如果模型存在bug导致保存过程失败,会出现xml文件的内容全部清空的情况,这样做很不保险,因此需要对出现异常情况要能做到恢复到修改前的样子,其做法是对XMLResourceImpl这个实现类的public void save(Map options) throws IOException方法进行复写,下面是我的做法:
java 代码
  1. public void save(Map options) throws IOException {   
  2.   
  3.     URIConverter uriConverter = getURIConverter();   
  4.     URI url = getURI();   
  5.     OutputStream os = uriConverter.createOutputStream(url);   
  6.   
  7.     StringBuffer sb = new StringBuffer();   
  8.     InputStream is = null;   
  9.     try {   
  10.         is = uriConverter.createInputStream(url);   
  11.     } catch (Exception e) {   
  12.         // 当创建文件时,由于文件还未存在而抛出的异常   
  13.     }   
  14.   
  15.     if (is != null) {   
  16.         byte[] b = new byte[4096];   
  17.         for (int n; (n = is.read(b)) != -1;) {   
  18.             sb.append(new String(b, 0, n));   
  19.         }   
  20.     }   
  21.   
  22.     try {   
  23.         save(os, getOptions(options));   
  24.     } catch (Exception e) {   
  25.         // 保存失败,恢复修改前的内容   
  26.         os.write(sb.toString().getBytes());   
  27.         throw new RuntimeException(e);   
  28.     } finally {   
  29.         if (is != null)   
  30.             is.close();   
  31.         os.close();   
  32.     }   
  33. }  
评论
发表评论

您还没有登录,请登录后发表评论

macrochen
搜索本博客
我的相册
2e63d5cc-792f-3ac0-a95c-695e20b4f5cd-thumb
P1100915
共 146 张
存档
最新评论