Classpath resource within jar

后端 未结 3 2026
别那么骄傲
别那么骄傲 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:12

    Use getResource instead of getSystemResource to use a resource specific to a given classloader instead of the system. For example, try any of the following:

    URL resource = getClass().getClassLoader().getResource("R.txt");
    URL resource = Foo.class.getClassLoader().getResource("R.txt");
    URL resource = getClass().getResource("/R.txt");
    URL resource = Foo.class.getResource("/R.txt");
    

    Note the leading slash when calling Class.getResource instead of ClassLoader.getResource; Class.getResource is relative to the package containing the class unless you have a leading slash, whereas ClassLoader.getResource is always absolute.

提交回复
热议问题