简体   繁体   中英

ClassLoader.getSystemResourceAsStream giving null exception

So I have this:

parser.parse(ClassLoader.getSystemResourceAsStream("/XML64_Decoded/res/sample.xml"), handler);

and I am getting this error:

Exception in thread "main" java.lang.IllegalArgumentException: InputStream cannot be null
at javax.xml.parsers.SAXParser.parse(Unknown Source)
at vms.main(vms.java:26)

It seems the code is not able to get InputStream in your case and the following line may be causing it:

ClassLoader.getSystemResourceAsStream("/XML64_Decoded/res/sample.xml")

It returns an instance of InputStream and I was facing the same problem. Before we proceed we need to figure out the location of xml file. If it is in same package as the class having this code is or in some other package. For example I am using this code in class SAXParserDemo and I have two xml files: employee.xml and employeeInPckg.xml . The first file is next to my class SAXParserDemo ie in same package so I can get InputStream using:

InputStream is1 = SAXParserDemo.class.getResourceAsStream("employee.xml");

The other file employeeInPckg.xml is at location src/files/employee/xml/employeeInPckg.xml and I can get InputStream as:

InputStream is2 = lassLoader.getSystemClassLoader().getSystemResourceAsStream("files/employee/xml/employeeInPckg.xml");

The rules for searching are explained in the javadoc of ClassLoader#getResource(String) and the javadoc of Class#getResource(String) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM