Classpath resource within jar

后端 未结 3 2024
别那么骄傲
别那么骄傲 2020-11-28 07:08

I have a project A, which contains some java files and a classpath resource R.txt. Within the project I use ClassLoader.getSystemResource(\"R.txt\"); to retrieve R.txt.

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 07:20

    Apparently your JAR is not loaded by the system classloader, so getSystemResource() can't work. This should work:

    ClassFromProjectA.class.getClassLoader().getResource("R.txt")
    

    IMO more convenient is putting resources inside the same package as the classes that use them, so you can use the shorter

    ClassFromProjectA.class.getResource("R.txt")
    

    (or, inside that class just getClass().getResource("R.txt"))

提交回复
热议问题