
写两个方法在这里,做个记录,免得以后忘了;
public void save(IFileDelegate file, Object object) throws IOException {
SysDesignDiagram designDiagram = (SysDesignDiagram) object;
if(StringUtils.isEmpty(designDiagram.getName())){
String path = FileUtil.toPackageWithoutExtension(file.getSourceRelativePath());
designDiagram.setName(path);
}
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
Resource resource = this.createResource();
SysDesignFactory SysDesignFactory = new SysDesignFactoryImpl();
DocumentRoot documentRoot = (DocumentRoot) SysDesignFactory
.createDocumentRoot();
documentRoot
.getMixed()
.add(
SysDesignPackage.Literals.DOCUMENT_ROOT__SYS_DESIGN_DIAGRAM,
object);
resource.getContents().add(documentRoot);
resource.save(outStream, getOptions());
ByteArrayInputStream inStream = new ByteArrayInputStream(outStream
.toByteArray());
try {
if(!file.exists())
file.create(inStream);
else
file.setContents(inStream);
} catch (Exception e) {
throw new IOException("save file error.");
} finally {
IOUtils.closeQuietly(inStream);
}
}创建资源
protected Resource createResource() {
ResourceFactoryImpl resourceFactory = new SysDesignResourceFactoryImpl();
return resourceFactory.createResource(URI
.createURI(SysDesignPackage.eNS_URI));
}


public Object parse(IFileDelegate file, IProgressMonitor monitor)
throws ModelParseException {
if (file.exists()) {
InputStream inStream = null;
try {
inStream = file.getContents();
SysDesignDiagram diagram = (SysDesignDiagram) this.parse(
inStream, monitor);
return diagram;
} finally {
IOUtils.closeQuietly(inStream);
}
}
return null;
}
本文介绍了两种用于处理文件的方法:一种是将对象保存到文件中,包括设置文件名、创建资源并保存内容;另一种是从文件中解析对象。涉及的技术包括输入输出流操作、异常处理及资源工厂的使用。

9296

被折叠的 条评论
为什么被折叠?



