The whole idea of getting object that loaded our class is to be able to get resources independently from current system setup, from current absolute paths.
You get null in getResourceAsStream
because file couldn't be found. Just make path to student.xml
relative, or absolute to classpath as Kayaman suggested.
this.getClass()
.getClassLoader()
.getResourceAsStream("path/to/file/student.xml")
You get file by classLoader.getResourceAsStream
with the same path search order that was used to load current class. Please see javadoc for getResource:
java.lang.ClassLoader.getResource(String name)
Finds the resource with the given name. A resource is some data
(images, audio, text, etc) that can be accessed by class code in a way
that is independent of the location of the code.
The name of a resource is a '/'-separated path name that identifies
the resource.
This method will first search the parent class loader for the
resource; if the parent is null the path of the class loader built-in
to the virtual machine is searched. That failing, this method will
invoke findResource(String) to find the resource.
Thanks to this generalization, code is more portable, doesn't matter if you are on Windows or Linux, or even on some distributed system. More on loading classes and possible sources: java.lang.ClassLoader