简体   繁体   English

Class.getResourceAsStream()问题

[英]Class.getResourceAsStream() issue

I have a JAR-archive with java classes. 我有一个带有java类的JAR-archive。 One of them uses some resource that is embedded into the same JAR. 其中一个使用嵌入到同一JAR中的一些资源。 In order to load that resource I use 为了加载我使用的资源

MyClass.class.getResourceAsStream(myResourceName);

One thing that bothers me though is whether it is guaranteed that required resource will be loaded from within the same JAR. 但困扰我的一件事是,是否保证从同一个JAR中加载所需的资源。 The documentation for "getResourceAsStream()" method (and corresponding ClassLoader's method) is not really clear to me. “getResourceAsStream()”方法(以及相应的ClassLoader方法)的文档对我来说并不是很清楚。

What would happen if there's a resource with the same name located somewhere in JVM classpath before my JAR? 如果在我的JAR之前有一个具有相同名称的资源位于JVM类路径中的某个位置,会发生什么? Will that resource be loaded instead of the one embedded in my JAR? 是否会加载该资源而不是我的JAR中嵌入的资源? Is there any other way to substitute resource embedded in JAR? 有没有其他方法来替换JAR中嵌入的资源?

Yes. 是。 The first matching resource found on the class path is returned, just like an executable search path. 返回类路径上找到的第一个匹配资源,就像可执行搜索路径一样。 This is why resources are often "namespaced" by putting them in directories that mirror the package structure of the library or application. 这就是为什么资源通常通过将它们放在镜像库或应用程序的包结构的目录中来“命名空间”的原因。

This behavior may be slightly different in the presence of custom classloaders (say in OSGi), but for vanilla Java apps, it is the case. 在存在自定义类加载器(例如在OSGi中)时,此行为可能略有不同,但对于vanilla Java应用程序,情况就是这样。

It works much the same way as for finding class files. 它的工作方式与查找类文件的方式大致相同。 So first try the parent class loader (recursively) then do whatever the class loader implementation does to find files. 所以首先尝试父类加载器(递归),然后执行类加载器实现所做的任何事情来查找文件。

There is no checking of the immediate caller class loader (as ResourceBundle does - see section 6.3 of the Java Secure Coding Guidelines ). 没有检查直接调用者类加载器(如ResourceBundle所做的那样 - 参见Java安全编码指南的第6.3节)。 However, you do need permissions to open the URL , as ClassLoader.getResourceAsStream just calls URL.openStream in the default implementation. 但是,您确实需要打开URL权限,因为ClassLoader.getResourceAsStream只是在默认实现中调用URL.openStream

Specify the package. 指定包。 Assuming you use com.yourcompany.file it SHOULD be unique. 假设你使用com.yourcompany.file它应该是唯一的。 (Unless someone WANTS to override your config file via the classpath.) (除非有人想通过类路径覆盖你的配置文件。)

如果只想从特定的JAR读取文件,可以打开JarFile并直接读取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM