Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 679
user63898 Avatar asked Dec 19 '12 18:12

user63898


People also ask

How to create db properties file in java?

Creating a .properties file −Instantiate the Properties class. Populate the created Properties object using the put() method. Instantiate the FileOutputStream class by passing the path to store the file, as a parameter.


1 Answers

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));
like image 50
Perception Avatar answered Oct 05 '22 03:10

Perception