我想使用JAXB使用指定的XML Schema文件创建XML文档。当我在Eclipse中运行我的应用程序时,它运行正常。后来我建了一个可运行的罐子。应用程序运行良好但是当我尝试保存文件时出现错误,这在Eclipse中不存在: MalformedByteSequenceException:4字节UTF-8序列的字节2无效
有一些功能负责整个过程:
private String generateXML() throws JAXBException, BladWalidacjiXml {
JAXBContext jaxbContext = JAXBContext
.newInstance(RootClass.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter xmlDocument = new StringWriter();
jaxbMarshaller.marshal(rootClass, xmlDocument);
String xml = xmlDocument.toString();
try {
XmlParser.validateWithXSD(xml);
} catch (SAXException e) {
throw new BladWalidacjiXml(e);
} catch (IOException e) {
throw new BladWalidacjiXml(e);
}
return xml;
}
public static void validateWithXSD(String xml) throws SAXException, IOException {
validate(new StreamSource(new ByteArrayInputStream(xml.getBytes())));
}
private static boolean validate(StreamSource xmlFile) throws SAXException, IOException{
File schemaFile = new File(SCHEMA_FILE_PATH);
SchemaFactory schemaFactory = SchemaFactory
.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = schemaFactory.newSchema(schemaFile);
javax.xml.validation.Validator validator = schema.newValidator();
validator.validate(xmlFile);
return true;
}
XML中的节点可能包括波兰国家标志,如“±”,“ę”,“ź”等。我想这不是错误的原因,但也许我错了。
如果有任何帮助,我将不胜感激。
编辑: 创建XML文件的代码:
public void saveToFile() throws JAXBException, IOException,
BladWalidacjiXml {
PrintWriter ostream = null;
boolean deleteFile = false;
try {
ostream = new PrintWriter("file.xml", "UTF-8");
ostream.write(generateXML());
} catch (JAXBException e) {
deleteFile = true;
throw e;
} catch (IOException e) {
deleteFile = true;
throw e;
} catch (BladWalidacjiXml e) {
deleteFile = true;
throw e;
} finally {
if (ostream != null) {
ostream.close();
}
}
}