Quantcast
Channel: Developer Feed - Snippet
Viewing all articles
Browse latest Browse all 178

Load Properties from Classpath

$
0
0

Classpath loader

Loading properties is easy as long as you know the path to the properties file. This can be issue at times when you either don't know the exact location of the file or it can change based on environment. In this case loading such file using the classpath loader turns out to handy. As long as the directory containing the file is in the classpath the loader can find it without us specifying the the exact path.<!--break-->

 

package com.livrona.snippets.io;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
* This snippet shows how to load a properties file
* located in the class path of the JVM.
*
* @author mvohra
*
*/

publicclass ClassPathPropertyLoader {

/**
* load the properties from the file
* and returns a Properties Object
* @return
* @throws IOException
*/

public Properties load(String propertyFileName) throws IOException {

// get the input stream of the properties file
InputStream in = ClassPathPropertyLoader.class.getClassLoader()
.getResourceAsStream(propertyFileName);

// error in case file is not found
if (in ==null) {
thrownew IOException("Input Stream handle to file is [null]");
}

// create the properties object and load in
Properties props =new java.util.Properties();
props.load(in);

return props;
}

/**
* Entry point, Test method
* @param args
* @throws Exception
*/

publicstaticfinalvoid main(String args[]) throws Exception {

String propertyFileName ="config.properties";

// create instance and load it
ClassPathPropertyLoader loader =new ClassPathPropertyLoader();
Properties properties = loader.load(propertyFileName);

// print out properties
System.out.print(properties.toString());

}

}




Viewing all articles
Browse latest Browse all 178

Trending Articles