在对EMF模型保存成xml文件的时候,有时候如果模型存在bug导致保存过程失败,会出现xml文件的内容全部清空的情况,这样做很不保险,因此需要对出现异常情况要能做到恢复到修改前的样子,其做法是对XMLResourceImpl这个实现类的public void save(Map options) throws IOException方法进行复写,下面是我的做法:
java 代码
- public void save(Map options) throws IOException {
- URIConverter uriConverter = getURIConverter();
- URI url = getURI();
- OutputStream os = uriConverter.createOutputStream(url);
- StringBuffer sb = new StringBuffer();
- InputStream is = null;
- try {
- is = uriConverter.createInputStream(url);
- } catch (Exception e) {
- // 当创建文件时,由于文件还未存在而抛出的异常
- }
- if (is != null) {
- byte[] b = new byte[4096];
- for (int n; (n = is.read(b)) != -1;) {
- sb.append(new String(b, 0, n));
- }
- }
- try {
- save(os, getOptions(options));
- } catch (Exception e) {
- // 保存失败,恢复修改前的内容
- os.write(sb.toString().getBytes());
- throw new RuntimeException(e);
- } finally {
- if (is != null)
- is.close();
- os.close();
- }
- }