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. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值