无法使用XML文件。 InputStream为null

我在这做错了什么? 我收到错误,输入流中没有任何内容,但事实并非如此。 文件在那里,标题正确。 我想抓住我放在XML文件中的IP地址。 是否有更好的方法来解析文件而不是dBuilder.parse(XMLReader.class.getResourceAsStream("C:\\Tools\\CLA\\test.xml"));

我遇到了这个例外:

 Caused by: java.lang.IllegalArgumentException: InputStream cannot be null at javax.xml.parsers.DocumentBuilder.parse(Unknown Source) at com.Intel.ameier.XMLparser.TryXML(XMLparser.java:17) 

这是代码:

 import java.io.IOException; import org.xml.sax.*; import org.w3c.dom.*; import javax.xml.parsers.*; public class XMLparser { protected void TryXML() throws ParserConfigurationException, SAXException, IOException{ DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = builderFactory.newDocumentBuilder(); Document document = dBuilder.parse(XMLReader.class.getResourceAsStream("C:\\Tools\\test.xml")); document.normalize(); NodeList rootNodes = document.getElementsByTagName("info"); Node rootNode = rootNodes.item(0); Element rootElement = (Element)rootNode; NodeList compList = rootElement.getElementsByTagName("computer"); for(int i = 0;i < compList.getLength(); i++){ Node computer = compList.item(i); Element compElement = (Element)computer; Node theIP = compElement.getElementsByTagName("ipaddress").item(0); Element theIpElement = (Element)theIP; System.out.println("The comptuer ip is : " + theIpElement.getTextContent()); } } } 

XML文件:

       111.11.11.6   111.11.11.5   111.11.11.3   

这与XML无关。 你正在使用Class.getResourceAsStream ,这是为了从该类的类加载器的类路径中加载一个资源……但是你要传入一个文件名

如果要为文件创建输入流,只需使用FileInputStream

 Document document = dBuilder.parse(new FileInputStream("C:\\Tools\\test.xml")); 

或者更好,为了关闭流:

 Document document: try (InputStream stream = new FileInputStream("C:\\Tools\\test.xml")) { document = dBuilder.parse(stream); } 

它确实与XML无关,Jon的答案令人满意。

但是,解释是不准确的。 可以使用Class.getResourceAsStream来加载任意文件。 在某些情况下, Class.getResourceAsStream是加载资源的首选方式。

这里的问题是Class.getResourceAsStream()将其参数解释为相对于类路径中的每个路径,并且不理解在此传递的绝对路径。 它只能“看到”类路径中的文件。

您可以尝试将C:\Tools\CLA到类路径中,然后使用

 getResourceAsStream("/test.xml");