-1

I have a package located at com.foo.bar. Inside this package I have a config.properties file, and a Test.java class. I'm trying to simply load the properties file into an input stream. I have tried this:

InputStream is = Test.class.getClassLoader().getResourceAsStream("config.properties");
System.out.println("stream: " +  is );

And also:

String path = "com.foo.bar.config.properties";
InputStream is = Test.class.getClassLoader().getResourceAsStream(path);
System.out.println("stream: " +  is );

In both cases, I get:

stream: null

as the value. No exception is thrown.

What am I doing wrong?

Ali
  • 261,656
  • 265
  • 575
  • 769
  • `com.foo.bar.config.properties` is *not* a path. Try providing the absolute path – Nir Alfasi Aug 01 '14 at 06:27
  • It works for me with `com/foo/bar/config.properties` so maybe you have a problem elsewhere – morgano Aug 01 '14 at 06:36
  • @morgano yes, that worked. previously my `resources` directory was not added to the pom.xml, so it wasn't being compiled into the jar. adding it to pom fixed it. – Ali Aug 01 '14 at 06:39
  • possible duplicate of [What is the difference between Class.getResource() and ClassLoader.getResource()?](http://stackoverflow.com/questions/6608795/what-is-the-difference-between-class-getresource-and-classloader-getresource) – Joe Sep 28 '14 at 10:25

1 Answers1

4

Try with this:

InputStream is = Test.class.getClassLoader().getResourceAsStream("com/foo/bar/config.properties");

important to mention: don't use a '/' at the beginning (it's a commont mistake)

morgano
  • 17,210
  • 10
  • 45
  • 56
  • that worked, but since they're in the same package, shouldn't just `config.properties` work too? – Ali Aug 01 '14 at 06:36
  • @ClickUpvote the parameter for `getResourceAsStream(String id)` is an identifier rather than a file path, so your resource (your properties file) has the identifier `com/foo/bar/config.properties` – morgano Aug 01 '14 at 06:40
  • @that's why you don't use a '/' at the beginning :-) – morgano Aug 01 '14 at 06:40