0

I want to read a property file from a java class file which the both are packed together as a same jar.

Project Structure:

src  
--->com  
------->xyz  
----------->Property(foldername)  
-------------------------------------->abc.properties  
----------->JavaClassFileFolder  
-------------------------------------->a.java

In the above structure folder, i want to read a abc.properties file from a.java file. I tried below methods in a.java file to read.

Method1:

InputStream in = this.getClass().getClassLoader().getResourceAsStream("com/xyz/Property/abc.properties");  
Properties prop =  new Properties();  
prop.load(in);

Result: Throws NPE at prop.load(in)

Method 2:

ClassLoader cl = Constants.class.getClassLoader();
Properties prop =  new Properties();   
prop .load(cl.getResourceAsStream("com/xyz/Property/abc.properties"));

Result: Throws NPE at prop.load(in)

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
Manigandan
  • 5,004
  • 1
  • 28
  • 47
  • If you're using Eclipse, you will need to place the resource in a directory at the package root...You'll need to find an Eclipse reference to get the full details. If you have the Jar file, try unzipping it and checking that the `abc.properties` exists where you expect to it – MadProgrammer Feb 07 '14 at 06:31

5 Answers5

1

It should work. The only reason it wouldn't is that com/xyz/Property/abc.properties is not in the jar

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
1

Start the path with a /, see this.getClass().getClassLoader().getResource("...") and NullPointerException.

That said:

  • If you use Maven, put your property files to src/main/resources/com/xyz/property. Maven will do the necessary copying for you.
  • Always begin your Java package names with a lower case letter, i.e. use property instead of Property. Normally, you expect only Java classes to begin with a capital letter.
  • Usually, it is not necessary to work with the classloader, use Constants.class.getResourceAsStream("/com/xyz/property/abc.properties") instead.
Community
  • 1
  • 1
Peter Keller
  • 7,526
  • 2
  • 26
  • 29
0

your method one has to work as far as this refers to class a and properties file is present at the destination you mentioned

dev2d
  • 4,245
  • 3
  • 31
  • 54
0

You are using a relative path (no / at the beginning), therefore getResourceAsStream starts from the package of your Object (this). Add the / at the beginning and you are searching classpath absolute and because you are in the same Classloader (your Class and your Property - File are in the same jar) here are no issues as well.

wumpz
  • 8,257
  • 3
  • 30
  • 25
0

There might be an exception thrown while trying to read the InputStream object value. Try using a throws IOException class.