gpt4 book ai didi

java - "Premature end of file"从网络解析 xml

转载 作者:行者123 更新时间:2023-11-29 06:00:48 29 4
gpt4 key购买 nike

当我尝试以这种方式解析来自网络的 XML 文件时:

URL url = new URL("http://www.nbp.pl/kursy/xml/a074z120416.xml");
URLConnection uc = url.openConnection();
saxParser.parse(uc.getInputStream(), handler);

过早的文件结束异常被抛出。

堆栈跟踪:

org.xml.sax.SAXParseException: Premature end of file.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLScanner.reportFatalError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at javax.xml.parsers.SAXParser.parse(Unknown Source)
at javax.xml.parsers.SAXParser.parse(Unknown Source)
at com.pmajcher.xmltest.ReadXMLFile.main(ReadXMLFile.java:142)

但是当我先将该 xml 保存到本地文件,然后尝试解析它时,一切正常。

URL url = new URL("http://www.nbp.pl/kursy/xml/a074z120416.xml");
URLConnection uc = url.openConnection();
InputStreamReader input = new InputStreamReader(uc.getInputStream());
BufferedReader in = new BufferedReader(input);
File file = new File("temp.xml");

if(!file.exists()){
file.createNewFile();
}

PrintWriter out = new PrintWriter(file);
String inputLine;

while ((inputLine = in.readLine()) != null) {
out.print(inputLine);
}
out.close();
saxParser.parse("temp.xml", handler);

我尝试从网络解析 xml 的方式有什么问题?

最佳答案

问题中你写的代码运行良好

URL url = new URL("http://www.nbp.pl/kursy/xml/a074z120416.xml");
URLConnection uc = url.openConnection();
saxParser.parse(uc.getInputStream(), handler);

我在这里看不到任何问题。也许当您第一次尝试时文件正在更改并且不完整。

但现在我可以向您确认它有效。我试试。

关于java - "Premature end of file"从网络解析 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10179068/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com