user63898
user63898

Reputation: 30885

Loading a properties file from a path that is not in my class path

Hmm simple task but how do i load properties file from path that is not in my class path?

for example: i have simple java file that i execute like this : foo.jar d:/sample/dir/dir/app1.properties and in the code i do :

 public boolean InitConfig(String propePath) {
         prop = new Properties(); 
         try {

            InputStream in =  this.getClass().getClassLoader().getResourceAsStream(propePath);
            prop.load(in);
            return true;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
     }

where propePath is : d:/sample/dir/dir/app1.properties
and InputStream in is always null. why does this happen?

Upvotes: 12

Views: 24307

Answers (1)

Perception
Perception

Reputation: 80593

The only resources that can be loaded by Classloader.getResourceAsStream are ones in the class (loaders) path. To read properties from an arbitrary path use one of the load functions of the Properties class itself.

final Properties props = new Properties();
props.load(new FileInputStream(filePath));

Upvotes: 27

Related Questions