Search code examples
javajarclassloader

Access resource from inside jar


I got a jar file test.jar that contains a folder resources which contains txtFile.txt.

I'm trying to access the file but the file seems to be null.

package main;

import java.net.URL;

public class Test {

    private Test() {
        URL file = this.getClass().getClassLoader().getResource("/resources/txtFile.txt");
        System.out.println(file == null);
    }

    public static final void main(String[] args) {
        new Test();
    }
}

Solution

  • Try using getResource("resources/txtFile.txt"); (i.e. without the first /).

    There should not be a leading slash when using the ClassLoader's version of getResource, it will be interpreted as an absolute path always.