0

I am getting File not found when reading config.properties. config.properties is rightly there under com/wu/resources. What could be the issue?

Properties prop = new Properties();

InputStream input;
input = Readproperties.class.getClassLoader().getResourceAsStream("/com/wu/resources/config.properties");
if (input != null) {
  prop.load(input); }
else {
  System.out.println("file not found");
}
  • 1
    try input = Readproperties.class.getClassLoader().getResourceAsStream("config.properties"); – Nick Isaacs Feb 19 '16 at 11:24
  • 4
    Drop the leading `/` - you're calling `ClassLoader.getResourceAsStream()`, not `Class.getResourceAsStream()`. – Jon Skeet Feb 19 '16 at 11:26
  • @wero - /com/wu/resources is under src ...is there a way to attach screenshot here? – Panayappan Swaminathan Feb 19 '16 at 11:27
  • @Nick - Read.properties and config.properties are in different packages,so putting direct value of config.properties also doesnt work – Panayappan Swaminathan Feb 19 '16 at 11:28
  • Possible duplicate of [NullPointerException when reading a properties file in Java](http://stackoverflow.com/questions/3139532/nullpointerexception-when-reading-a-properties-file-in-java) – Harshad Feb 19 '16 at 11:30
  • Okay, then you will have to provide relative path and not absolute path – Nick Isaacs Feb 19 '16 at 11:30
  • @PanayappanSwaminathan did you put it in `src/main/resources` or just in `src` ? – rve Feb 19 '16 at 12:09
  • @JonSkeet - Thanks, after removing / , it worked. How does this / makes difference between Class and Class loader – Panayappan Swaminathan Feb 19 '16 at 12:24
  • In `Class.getResourceAsStream`, "/" is used to "root" the resource name, because otherwise it will be treated as relative to the class. That's not the case for `ClassLoader`, because there's no class for it to be relative to. See the docs for more details. – Jon Skeet Feb 19 '16 at 12:37

2 Answers2

0

It seems ClassLoader.getResourceAsStream(String name) returns null, which then causes Properties.load to throw NullPointerException.

URL getResource(String name): Finds the resource with the given name. A resource is some data (images, audio, text, etc) that can be accessed by class code in a way that is independent of the location of the code. The name of a resource is a '/'-separated path name that identifies the resource.

Returns : A URL object for reading the resource, or null if:

  • the resource could not be found, or
  • the invoker doesn't have adequate privileges to get the resource.
Nikita Mittal
  • 35
  • 2
  • 10
0

try

input = Readproperties.class.getClassLoader().getResourceAsStream("src/com/wu/resources/config.properties");
Raphael Roth
  • 26,751
  • 15
  • 88
  • 145