I am writing a program which will read a properties file.
I craeted the properties file and placed it in the same location of the class file.
But when I am trying to run the program from eclipse, it can't find the properties file, but if I specify the full path of the properties file, it can read it.
Could anyone please tell how to set the path of the properties file, so that I don't need to specify the full path when reading it.
Thanks,

Recommended Answers

All 2 Replies

Specifying a full path guarantees that your app won't run on another machine, and using the class path won't work if multiple users are running the same app.
Much better to use

System.getProperty("user.home")

to get a reference to the user's home directory, and put the file there, eg

new File(System.getProperty("user.home") + "/myLogFile.txt");

This will (should) work an all known systems.
ps Check out System.getProperty for other alternate locations.

Could anyone please tell how to set the path of the properties file, so that I don't need to specify the full path when reading it.

Specify it relative to the class which would be using it or relative to your project package hierarchy.

Relative to your class: Ensure that the properties file is present in the same package as the class trying to load the properties file. Then do something like:

Properties props = new Properties();
props.load(getClass().getResourceAsStream("test.properties"));

Relative to your package hierarchy: Create a separate package for keeping your properties configuration e.g. test.config. Now to load your properties file from any class, use:

Properties props = new Properties();
props.load(getClass().getClassLoader().
  getResourceAsStream("test/config/test.properties"));

Both these methods would almost always work irrespective of the OS which you are distributing your JAR to since the paths are relative to the class/working directory. Of course, the second method has the advantage of the properties files being reused across classes without altering the code.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.