Differences between getClass(). getResourceAsStream() and getClass(). getClassLoader(). getResourceAsStream()

Asked

Viewed 6,209 times

18

In the need to load a resource in my project I came across these two methods. From the choice between one of the two arose some doubts about which I would like to share here.

  • What is the motivation or in which scenario each should be used?
  • Is there any head start from one relationship to another? If so, what would this be?
  • 2

    Good question, +1!

1 answer

15


The difference between how the value passed as argument is interpreted is very subtle.

Basically, you have two different methods: ClassLoader.getResourceAsStream() and Class.getResourceAsStream(). These two methods will locate the resource differently.

Class.getResourceAsStream()

In Class.getResourceAsStream(caminho), the path is interpreted as a local path for the class package that you are the method.

For example, by calling String.class.getResourceAsStream("file.txt") a file will be searched in your classpath in the following location: java/lang/file.txt.

If the path begins with a /, then it will be considered an absolute path and start searching from the root of the classpath.

So calling String.class.getResourceAsStream("/file.txt") the file will be searched at the following location: ./myfile.txt.

Classloader.getResourceAsStream(path)

Already in ClassLoader.getResourceAsStream(caminho), implementation will consider all paths to be absolute.

So calling String.class.getClassLoader().getResourceAsString("myfile.txt") and String.getClassLoader().getResourceAsString("/myfile.txt"), both will search for the same file on classpath, at the following location: ./myfile.txt.

Is there any advantage of one relationship to another? If so, what would it be this?

Well, it depends a lot on your requirements, details of your application, initially the most obvious is that, to load files within the same package of your class, you must use: Class.getResourceAsStream().

I recommend reading the following article, it is very interesting: Smartly load your properties

Browser other questions tagged

You are not signed in. Login or sign up in order to post.