0

※ I have looked at the old questions and none fixed my problem.

I am having an issue of getResourceAsStream returning null. It works in Eclipse but not when I use the project as a jar file.

The jar file has a folder name config and in the folder config, there is a config file. I try to import the config file using the code below.

file = "/" + new File(configFolder, configFileName).getPath();
in = this.getClass().getResourceAsStream(file);

The jar worked before. But now that I changed my codes and put the code above in an abstract class. It isn't working. getResourceAsStream is returning null.

I tried MyAbstractClass.class.getResourceAsStream(file) but still it isn't working.

user207421
  • 305,947
  • 44
  • 307
  • 483
lw29
  • 101
  • 2
  • Do you have more than one JAR? – user253751 Mar 18 '15 at 03:33
  • Print out `file`. Make sure it really points to an existing file inside of the JAR. – Thilo Mar 18 '15 at 03:43
  • I had only one jar. Printing file gives "/config\configfilename.txt". Do I need to use "/"? – lw29 Mar 18 '15 at 03:45
  • 1
    get rid off the backslash, yes. Don't use File to construct the path. Just concatenate the Strings. – Thilo Mar 18 '15 at 04:27
  • Thank you. I changed to string concatenation and it is working now. Could you please add this into your answer so I could accept it? :) – lw29 Mar 18 '15 at 05:12
  • possible duplicate of [ClassLoader.getResource() doesn't work from .jar file](http://stackoverflow.com/questions/1664073/classloader-getresource-doesnt-work-from-jar-file) – Kenster Mar 20 '15 at 18:02

2 Answers2

1

You are running into class loader issues. Use this.getClass().getClassLoader().getResourceAsStream(file);

If it still doesn't work, there's probably something wrong with your class path or the resource path.

Jilles van Gurp
  • 7,927
  • 4
  • 38
  • 46
  • This works for me, thanks Jilles! For the sake of completeness only, `MyAbstractClass.class.getClassLoader().getResourceAsStream(relativePath);` works as well. – Tob Feb 14 '22 at 20:10
0

Standard lone java applications, backslash could not be work for load the property file(config file). But it will work in web applications with backslash.