【发布时间】:2019-02-10 16:53:54
【问题描述】:
我有一个包含一些内容的 XML 文件。我想根据 REST 请求修改此文件。在创建新的 FileOutputStream 时,所有内容都被删除,稍后使用我的代码,我可以将所需的数据添加到 XML 文件中。 但是在创建一个新的 FileOutputStream 之后,如果抛出异常,所有的内容都会被删除。
如果抛出异常,如何保留 XML 文件(Abc.xml)中的原始内容?
FileOutputStream fileOutputStream = null;
try {
validateXMLSchema("Abc.xsd", "Abc.xml");
JAXBContext jc = JAXBContext.newInstance(Structure.class);
Marshaller marshaller = jc.createMarshaller();
fileOutputStream = new FileOutputStream(
new File(System.getProperty("rootPath") + "/WEB-INF/classes"
+ "/" + "Abc.xml"));
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Structure structure = new Structure();
structure.setName("Types");
ObjectFactory objectFactory = new ObjectFactory();
} catch (JAXBException e) {
throw IlmODataExceptionBuilder.buildODataApplicationException(
FILE_FORMAT_IS_INCORRECT_CREATE_FILE_AGAIN,
HttpStatusCode.BAD_REQUEST, "Abc.xml");
} catch (FileNotFoundException e) {
throw IlmODataExceptionBuilder.buildODataApplicationException(
FILE_NOT_FOUND, HttpStatusCode.BAD_REQUEST,
"Abc.xml");
} finally {
if (fileOutputStream != null) {
fileOutputStream.close();
}
}
这里的方法 validateXMLSchema() 只是验证 XML 模式。 任何帮助表示赞赏。
【问题讨论】:
标签: java jakarta-ee file-io jaxb fileoutputstream