简体   繁体   中英

Loading a resource file from a JAR, outside classpath, in IntelliJ

Assume an application developed in IntelliJ , to be packaged in a single JAR and use "resource" files that

  • Can be located in any package (not only in a resources folder)
  • May have non-standard file extensions (may even be Java files)
  • Are not present in all classpaths (eg, to avoid circular dependencies)

If a class (say, MyClass ) in a package (say, com.example.pack ) is given a path to such a "resource" that resides outside its classpath and attempts to access it via

 MyClass.class.getClassloader().getResourceAsStream(resourcePath);

the InputStream object returned in IntelliJ unit tests is (expectedly) null due to the classpath. However, when the code is executed it works, since everything is in the same JAR.

For example, bundling all the packages of the application in the same JAR (say, MyApplication.jar ) and running something like

java -cp MyApplication.jar com.example.pack.MyClass

from the command line, does produce a non- null InputStream .

Is there any way to configure IntelliJ to somehow "know" that all packages belong to the same JAR and thus treat them accordingly, so that the above call to getResourceAsStream() works?

The only way to configure that is to add the module containing the resource files as a dependency to the module containing the tests. Then IntelliJ IDEA will include that module into the runtime classpath of the tests, and the getResourceAsStream() call will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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