1

我想使用 JAXB 创建具有指定 XML 模式文件的 XML 文档。当我在 Eclipse 中运行我的应用程序时,它运行良好。后来我建立了可运行的jar。应用程序运行良好,但是当我尝试保存文件时出现错误,该错误在 Eclipse 中不存在: MalformedByteSequenceException: Invalid byte 2 of 4-byte UTF-8 sequence

有负责整个过程的功能:

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();
        }
    }
} 
4

0 回答 0