1

I have created a java project in which I am using a properties file also which is created inside a java packgae named abcedf

so package name is abcdef which consists a class name abc.java and a property file named drg.properties ,now from class abc.java i am referring to that properties file as..

abc tt = new abc();
URL url = tt.getClass().getResource("./drg.properties");
File file = new File(url.getPath());
FileInputStream fileInput = new FileInputStream(file);

now this file is referred and my program runs successfully but when I am trying to make it executable jar then this property file is not referred please advise what is went wrong while creating the property file.

2 Answers2

2

Use

tt.getClass().getResourceAsStream("./drg.properties");

to access the property file inside a JAR. You will get an InputStream as returned object.
-------------------------------------------------
Here is an example to load the InputStream to Properties object

InputStream in = tt.getClass().getResourceAsStream("./drg.properties");
Properties properties = new Properties();
properties.load(in); // Loads content into properties object
in.close();

If your case, you can directly use, the InputStream instead of using FileInputStream

dARKpRINCE
  • 1,538
  • 2
  • 13
  • 22
0

When you access "jarred" resource you can't access it directly as you access a resource on your HDD with new File() (because resource doesn't live uncompressed on your drive) but you have to access resource (stored in your application jar) using Class.getResourceAsStream()

Code will looks like (with java7 try-with-resource feature)

Properties p = new Properties();
try(InputStream is = tt.getClass().getResourceAsStream("./drg.properties")) { 
 p.load(is); // Loads content into p object
}
Luca Basso Ricci
  • 17,829
  • 2
  • 47
  • 69