getClass().getResource("/") returns null in command line

14,084

Solution 1

There are (often) no directories inside jar files. Therefor it will return null.


If you want to get the file you could get that resource directly:

URL fileUrl = getClass().getResource("/file.txt");
...

Or simply:

InputStream fileInputStream = getClass().getResourceAsStream("/file.txt");

Solution 2

You should move that file into your CLASSPATH and get it like this:

InputStream is = this.getClass().getResourceAsStream("file.txt");
Share:
14,084
user691197
Author by

user691197

Updated on June 04, 2022

Comments

  • user691197
    user691197 almost 2 years

    I'm trying to read a file in my maven project at /src/main/resources/file.txt.

    I'm using

    URL url=this.getClass().getResource("/");
    String filePath=url.getPath()+"file.txt";
    

    url object gets the correct value when this is run thru eclipse.

    But, when I package the jar and run it in command line:

    jar -cp myjar.jar SampleTest
    

    It returns null for 'url' object and throws a NullPointerException in the next line.

    I have openend my Jar file using file browser and checked. It has the 'file.txt' in "/" location inside the Jar.

    Where am I going wrong ?

  • duffymo
    duffymo almost 12 years
    You're assuming that's in the classpath. Does your JAR have a manifest, with Class Path entries? If not, add one.
  • user691197
    user691197 almost 12 years
    Well, it works fine in eclipse. "/" points to the /target/classes directory when run in eclipse.
  • dacwe
    dacwe almost 12 years
    As I wrote in my answer: There are no directories inside jar files - e.g. You cannot get a resource (directory) that doesn't exist. When you run the program from eclipse your classpath points to a file path/directory. In that environment you can get the directory information using Class.getResource.
  • user691197
    user691197 almost 12 years
    Is it possible to get a directory URL in a jar using getResource("/dir") by tweaking the project pom.xml some way ??
  • dacwe
    dacwe almost 12 years
    It is possible but a hack, see this page for more information.