Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why getResourceAsStream method is in Class class?

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.

like image 398
anupsth Avatar asked Jun 17 '10 11:06

anupsth


People also ask

What is the use of getResourceAsStream in Java?

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.

When using class getResourceAsStream Where will the resource be searched?

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.

Should we close getResourceAsStream?

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.

How do you specify a resource path in Java?

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.


2 Answers

There is a relationship to the class:

  • The package of the class is taken into account - if you give call getResourceAsStream("baz.txt") on the class for foo.bar.SomeClass it will look for /foo/bar/baz.txt
  • The classloader is taken into account to find the resources in the first place - if it were a static method, how would it know which jar files (etc) to look in? There's more to life than the system classloader
like image 75
Jon Skeet Avatar answered Oct 10 '22 15:10

Jon Skeet


It just give inputstream of file which is in jar file ...

Incorrect. Not all classloaders load resources from regular JAR file.

  • Some classloaders load from directories.
  • Some classloaders load from the network.
  • Some classloaders load from multiple sources.

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.

like image 2
Stephen C Avatar answered Oct 10 '22 13:10

Stephen C