25 November 2009

Loading properties files using Classloader

One problem I was facing last week while playing with a small client/server application was that I cannot refer to the relative path of properties files using eclipse.

Let me discuss the situation; I have a class called Constants that load a properties file that contains the server host and port:

public class Constants {

private static Logger logger = Logger.getLogger(Constants.class);

public static String HOST_NAME;
public static int PORT_NUMBER;

static {
try {
Properties jposAppProps = new Properties();
jposAppProps.load(new FileInputStream(new File("JposApp.properties")));
String host = jposAppProps.getProperty("server.host");
String port = jposAppProps.getProperty("server.port");

if (host == null || port == null)
throw new Exception("Invalid configuration");

HOST_NAME = host;
PORT_NUMBER = Integer.parseInt(port);

}catch(NumberFormatException ex) {
logger.fatal("Invalid configuration", ex);
catch (IOException ex) {
logger.fatal(ex.getMessage(), ex);
}catch(Exception ex) {
logger.fatal(ex.getMessage(), ex);

The problem appears in the line :
jposAppProps.load(new FileInputStream(new File("JposApp.properties")));

I have the JposApp.properties in the "src" directory, so when running this class from outside eclipse, everything goes well.
But from inside eclipse, eclipse needs me to provide an absolute path !! (may be there's a work-around way, but I don't know it)

But I recognized that, Web frameworks like JSF and JSPX-BAY, uses classloaders to load properties files, So, I choose that way.

So, I have replaced the line above by this one:

Really I have not much experience with class loaders, so this line may be abuse, but it really works.
Post a Comment