有和没有getClassLoader的getResourceAsStream有什么区别? [英] What is the difference between getResourceAsStream with and without getClassLoader?
问题描述
我想知道以下两者之间的区别:
MyClass.class.getClassLoader()。getResourceAsStream(path / to / my / properties);
和
MyClass.class.getResourceAsStream(path / to / my / properties);
谢谢。
来自Javadoc的 Class.getResourceAsStream()
:
此方法委托给该对象的类加载器。
在委托之前,使用此算法从给定的资源名称构造绝对资源名称:
- 如果
name
以'/'('\ u002f')开头,然后资源的绝对名称是'/'后面的名称部分。
- 否则,绝对名称的格式如下:
modified_package_name / name
其中modified_package_name是包名称这个对象用'/'代替'。'('\ u002e')。
换句话说,如果path以/开头,它们会做同样的事情,但如果没有,那么在后一种情况下,路径将相对于类的包,而类加载器将是绝对的。 / p>
简而言之,第一次提取路径/到/ my / properties
,第二次提取 package / of / myclass / path / to / my / properties
。
I'd like to know the difference between the following two:
MyClass.class.getClassLoader().getResourceAsStream("path/to/my/properties");
and
MyClass.class.getResourceAsStream("path/to/my/properties");
Thank you.
From the Javadoc for Class.getResourceAsStream()
:
This method delegates to this object's class loader. Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:
- If the
name
begins with a '/' ('\u002f'), then the absolute name of the resource is the portion of the name following the '/'.- Otherwise, the absolute name is of the following form:
modified_package_name/name
Where the modified_package_name is the package name of this object with '/' substituted for '.' ('\u002e').
In other words, they do the same thing if the "path" begins with a "/", but if not, then in the latter case, the path will be relative to the class's package, whereas the classloader one will be absolute.
In short, the first fetches path/to/my/properties
and the second fetches package/of/myclass/path/to/my/properties
.
这篇关于有和没有getClassLoader的getResourceAsStream有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!