0

So I was following this tutorial where I pretty much copy pasted the code from the SAX parser example. I created the same employees.xml file in the same folder as my java class. The error I get is Exception in thread "main" java.lang.IllegalArgumentException: InputStream cannot be null on this line of code:

parser.parse(ClassLoader.getSystemResourceAsStream("employees.xml"),handler);

You can view the rest of my code here if it's of any help: pastie link
Does anyone know how to make it read the xml file properly? Or if there are any other suggestions on a good way to parse XML in java please share. Thanks

seenukarthi
  • 8,241
  • 10
  • 47
  • 68
sjottil
  • 43
  • 6

3 Answers3

0

Instead of using ClassLoader, try using this :

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


source : http://www.coderanch.com/t/369908/java/java/ClassLoader-getSystemResourceAsStream

Thanks, Dev

Kena
  • 33
  • 1
  • 8
0

The documentation of the ClassLoader class for the getSystemResourceAsStream indicates that it returns a null when the resource can not be found.

So it is recommended to make sure, prior to calling parser.parse, to check that the result of getSystemResourceAsStream is not null.

The documentation also says

Open for reading, a resource of the specified name from the search path used to load classes.

So it means that it is not necessarily searching the directory where the current class file is located, but rather the general system CLASSPATH.

If you are just using pure Java, you can open a plain FileInputStream without a class loader. If you are aiming for a bean or some other implementation that dictates a dependence between the location of your class and the location of the XML file, use the current class's class loader as indicated in Dev G's answer.

RealSkeptic
  • 33,993
  • 7
  • 53
  • 79
0

You need to create a class folder, in eclipse you can see this, in netbeans see this, or without any IDE you can see this. Finally you want to try this:

parser.parse (SAXParserDemo.class.getResourceAsStream("/employees.xml"), handler);

instead of:

parser.parse(ClassLoader.getSystemResourceAsStream("employees.xml"), handler);

Community
  • 1
  • 1
Linus
  • 1,516
  • 17
  • 35