首页 > 解决方案 > 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 ; 

标签: javamultithreadingxml-parsing

解决方案


推荐阅读