我使用此方法验证存储一些配置信息的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:
它能以某种方式与线程相关吗? 谢谢大家
更新 我为文档构建器创建了错误处理程序,但它又说了
致命错误:文件过早结束