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

15

In need of loading a resource into my project I came across these two methods. From the choice of one of the two, there were some doubts that I would like to share here.

  • What is the motivation or in what scenario should each be used?
  • Is there a advantage of one relationship to the other? If so, what would this be?
asked by anonymous 30.06.2015 / 14:36

1 answer

12

The differences are subtle in how the file you pass in Path is interpreted.

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

Class.getResourceAsStream

In Class.getResourceAsStream (path), the path is interpreted as a local path to the class packet that you are in the method. For example, calling String.class.getResourceAsStream ("file.txt") will look for a file in your class path in the following location: "java / lang / file.txt". If the path starts with a /, then it will be considered an absolute path, and will begin to look up from the root of the classpath. Then by calling String.class.getResourceAsStream ("/ file.txt") the file will be searched at the following location: ./myfile.txt.

ClassLoader.getResourceAsStream (path)

ClassLoader.getResourceAsStream(caminho) , this method will already consider all paths to be absolute. So by calling String.class.getClassLoader().getResourceAsString("file.txt") and String.getClassLoader () getResourceAsString ("/myfile.txt"), both will look for the same file in the 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 should use: Class.getResourceAsStream

I recommend reading the following article, it's very interesting:

link

    
30.06.2015 / 15:44