Why public InputStream getResourceAsStream(String name) is in Class class? It just give inputstream of file which is in jar file and there is no relation with Class class. so it can be static method and it can be in any class.
The getResourceAsStream method returns an InputStream for the specified resource or null if it does not find the resource. The getResource method finds a resource with the specified name. It returns a URL to the resource or null if it does not find the resource. Calling java.
The java. lang. Class. getResourceAsStream() finds a resource with a given name.It returns a InputStream object or null if no resource with this name is found.
You should always close streams (and any other Closeable, actually), no matter how they were given to you. Note that since Java 7, the preferred method to handle closing any resource is definitely the try-with-resources construct.
The simplest approach uses an instance of the java. io. File class to read the /src/test/resources directory by calling the getAbsolutePath() method: String path = "src/test/resources"; File file = new File(path); String absolutePath = file.
There is a relationship to the class:
getResourceAsStream("baz.txt")
on the class for foo.bar.SomeClass
it will look for /foo/bar/baz.txt
It just give inputstream of file which is in jar file ...
Incorrect. Not all classloaders load resources from regular JAR file.
All of this complexity is hidden from you when you use the ClassLoader
API via Class
in this case.
... and there is no relation with Class class.
Incorrect. See @Jon Skeet's answer. Note that calling Class.getResourceAsStream(String)
gives a resource that belongs to the same security context as the class. This can be very important if there are multiple classloaders / security contexts in use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With