RaT
RaT

Reputation: 1194

Load a file from a specific directory

I have a specified URL that i cant change i.e.

/opt/local/java/config/npvr.properties

where should i place my file so that the following code can work:

String PROPERTIESFILEPATH1 = "/opt/local/java/config/npvr.properties";
File tmPropertiesFile = new File(PROPERTIESFILEPATH);
Properties properties = new Properties();

if (tmPropertiesFile.exists()) {
    .....
}

i have tried placing my file in directory shown below but it didn't work: enter image description here

My problem is that I can change only the location of property-file without changing the code to solve this problem. Please Help.

Upvotes: 0

Views: 697

Answers (3)

Sunil
Sunil

Reputation: 447

use getClass().getResourceAsStream to load property file from relative of class

public class Main {

     public static void main(String args[]) throws Exception{
         String PROPERTIESFILEPATH = "/opt/local/java/config/npvr.properties";
         //File tmPropertiesFile = new File(PROPERTIESFILEPATH);
         Properties properties = new Properties();
          InputStream ins=null;
          //ins=new FileInputStream(PROPERTIESFILEPATH);
          ins=new Main().getClass().getResourceAsStream(PROPERTIESFILEPATH);
         properties.load(ins);
         System.out.println(properties.get("Hello"));
     }
}

Upvotes: 1

Sandeep Bhardwaj
Sandeep Bhardwaj

Reputation: 1360

If you are using linux then add this file /opt/local/java/config/ directory location outside of your project.

"OR" in windows C:\opt\local\java\config\ here.

Upvotes: 2

ControlAltDel
ControlAltDel

Reputation: 35106

The file needs to go in /opt/local/java/config, not [projectdir]/opt/local/java/config. You are putting it in the wrong place

Upvotes: 3

Related Questions