7

I'm trying to load a properties file without using the actual path of the file. I've already done that on some other simple apps using:

InputStream inputStream = ClassLoader.getSystemResourceAsStream(PROPERTIES_FILE);
props.load(inputStream);

But this time it doesn't work. The inputStream is null for some reason. PROPERTIES_FILE is a constant defined as "app.properties". I tried to remove the .properties extension and got the same results.

Any ideas?

Thanks.

Lancelot
  • 2,417
  • 12
  • 39
  • 46

3 Answers3

13

The PROPERTIES_FILE constant should include the package as well as the properties file (e.g. "com/some/library/file.properties".

    final static String PROPS_FILE = "/com/some/library/file.props";
                     //The preceding  "/" is dependendant on wheterh 
                     //you are going to be giving a relative or absolute location
    InputStream is = YourCurrentClass.class.getResourceAsStream(PROPS_FILE);
jconlin
  • 3,806
  • 6
  • 31
  • 32
  • I've added the package information as you mentioned but still got the same error. BTW the method where I'm doing that call is static if that helps any... – Lancelot Apr 20 '09 at 21:20
  • Actually there was a typo when I added the package name. That solution worked great. Thanks! :) – Lancelot Apr 20 '09 at 21:23
  • 1
    You probably want to call getResourceAsStream on your class' class loader. Or probably on your class' Class. – Tom Hawtin - tackline Apr 20 '09 at 21:26
  • I believe the actual problem was he was using "ClassLoader.getSystemResourceAsStream" which looks for system resources. There is a slight difference. This is a good discussion: http://www.coderanch.com/t/369908//java/ClassLoader-getSystemResourceAsStream – markthegrea May 04 '10 at 14:52
  • I have the very same problem. I have a spring web application and I want to load an xml file for testing purposes. It is located at WebContent/WebContent/WEB-INF/classes/testing/document.xml I've tried InputStream is = getClass().getClassLoader().getResourceAsStream("WebContent/WEB-INF/classes/testing/document.xml"); but it ends with a null. I tried to omit the initial "/" but it's the same. What am I missing? – MaVVamaldo Mar 02 '12 at 14:57
0

Got the same problem.

Reason: I renamed DAO package to dao. While exploding the artifact, directory DAO not get overwritten.

So I got dao in project internals and DAO in filesystem :facepalm:

T. Short
  • 3,481
  • 14
  • 30
Gogogo
  • 1
  • 1
-1

When getSystemResourceAsStream returns null, it means the resource was not found. Make sure the requested resource really is on the classpath at the specified location.

erickson
  • 265,237
  • 58
  • 395
  • 493
  • It answers the question really precisly, but does not support helping to solve the problem. – Barny Jun 21 '22 at 12:13