java - XML 文件解析的文件过早结束异常经常发生但不经常发生。
问题描述
我目前正在尝试运行一个线程来从目录中读取文件并解析它。线程就是不断的监听目录并将监听到的文件发送给进程解析。
在使用 FTP 将文件连续放置在指定目录中时,我面临“文件过早结束 - org.xml.sax.SAXParseException”。
我试过检查文件传输是否完成,那里没有错误。我没有使用 inputSource/InputStream 来读取文件。除此之外,我确保我没有读取空文件。我只是使用 Dom 解析器解析方法来解析给定的文件。
我将附上 XML 文件和 java 程序以供进一步参考。
我读过很多博客和链接。然而,没有运气。任何帮助都会非常有帮助。
public class DirectoryWatcher implements Runnable {
private DocumentBuilderFactory factory;
private XPath xpath;
private Document doc;
public DirectoryWatcher() {
this.factory = DocumentBuilderFactory.newInstance();
this.factory.setNamespaceAware(true); // XML contains name space pattern. Hence without configuration of name
// space, XML will not be parsed
this.xpath = XPathFactory.newInstance().newXPath();
}
@Override
public void run() {
while (!cancel) {
try {
for (String file : directory.list(filter)) {
doc = factory.newDocumentBuilder().parse(directory.getAbsolutePath() + File.separator + file);
markAsProcessed(file);
TimeUnit.MILLISECONDS.sleep(interval);
}
} catch (InterruptedException e) {
cancel = true;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Error while parsing the file xx/parked.xml Premature end of file.
[Ljava.lang.StackTraceElement;@38661fd
org.xml.sax.SAXParseException; systemId: file:///home/sample.xml ;
解决方案
推荐阅读
- github-pages - 为什么不创建 github.io(github 页面)
- angular - 订阅时过滤器不适用于材料表
- api - 尝试通过 API 修补 Classroom 公告中的 TEXT
- css - 基于多个值的 React Native Animated 插值不透明度
- ruby-on-rails - Ruby/Rails 4.2 - 如果 A && B 其中 B 条件取决于 Rails 环境
- mongodb - 在MongoDB中计算每5秒的移动平均值
- python - 开始处理异步任务,同时将它们添加到事件循环中
- python - pySerial 和 Arduino 通信
- github - GitHub 中的图像不适用于自述文件
- jquery - jquery:计算字符数,对某些标签进行不同的计数