Thursday, November 17, 2016

Loading properties from default property file location in maven project

Sometimes loading the property from file becomes a headache to java developers and it starts giving some awful errors. Specially finding the correct path for the property file.
As per maven property files will be placed inside "resources" folder and these files are copied into 'classes' folder inside "WEB-INF" (WEB-INF\classes)

below is a java code block works fines taking the given property file from default location. (default =WEB-INF\classes)

Here property file is loaded using class loader and you need Java 7 to use this logic.
With this you can easily get rid of pain came from  Java 1.5

======================================================

String resourceName = "config.properties"; // could also be a constant
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Properties props = new Properties();
try (InputStream resourceStream = loader
.getResourceAsStream(resourceName)) {
props.load(resourceStream);
System.out.println(props);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


=============================================================

No comments:

Post a Comment