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