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
Good question, +1!
– Franchesco