我使用这种方法来验证存储一些配置信息的 xml 文件:
public static boolean isXmlFileWellFormed(File xmlFile) {
logger.log(Level.INFO, "isXmlFileWellFormed({0})", xmlFile);
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = builderFactory.newDocumentBuilder();
builder.parse(xmlFile);
return true; // document well formed
} catch (Throwable ex) {
logger.log(Level.WARNING, "Xml file is not well-formed: {0}", ex);
try {
FileUtils.streamToFile(new FileInputStream(xmlFile), "c:\\backup.xml");
} catch (IOException ex1) {
logger.log(Level.WARNING, "backup not created");
}
}
return false;
}
它很好地验证了 xml 文件,它看起来像
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<mountedFolders>
<folder path="C:\tmp\prezentacka\" recursively="false">
<document key="1636_0001_pdf_1.png;539777;1338204039646">
<state>NEW</state>
</document>
<document key="faktura.pdf;1102305;1336552599405">
<state>NEW</state>
</document>
<document key="prva strana_1361268270589.JPEG;276888;1361269977428">
<state>NEW</state>
</document>
</folder>
<folder path="C:\tmp\one2\" recursively="false">
<document key="1636_0001.pdf;280700;1336569165030">
<state>NEW</state>
</document>
<document key="1636_0001_pdf_1.png;539777;1338204039646">
<state>NEW</state>
</document>
<document key="1636_0001_pdf_2.png;565609;1338204041562">
<state>NEW</state>
</document>
<document key="1637_0001.pdf;121031;1336569168739">
<state>NEW</state>
</document>
<document key="faktura.pdf;1102305;1336552599405">
<state>NEW</state>
</document>
</folder>
<folder path="C:\tmp\" recursively="false">
<document key="faktura1.pdf;637590;1340007249059">
<state>NEW</state>
</document>
<document key="LicZmluva.pdf;41164;1340016186796">
<state>NEW</state>
</document>
</folder>
</mountedFolders>
也许它的格式不完全,但它应该是有效的。实际上,这个xml是在catch代码块中解析方法崩溃并出错后保存的backup.xml
[INFO] stderr.run: [Fatal Error] .mounted:1:1: Premature end of file.
[WARNING] XmlUtils.isXmlFileWellFormed: Xml file is not well-formed:
它可以以某种方式与线程有关吗?谢谢大家
更新 我为文档生成器创建了错误处理程序,但它又说
致命错误:文件过早结束