I am trying to read properties which is located external to the jar file of my code.using ResourceBundle
but its unable to read the property file locations.properties
. The property file is located under resource
folder and both jar
and resource
folder are under same directory.
myDir
--> myJar.jar
--> resource
-->locations.properties
I don't know whats wrong with my code below:
public static ResourceBundle getResourceBundle(String fileName) throws MalformedURLException{
if (resourceBundle == null) {
File file = new File("resource/"+fileName);
URL[] urls = { file.toURI().toURL() };
ClassLoader loader = new URLClassLoader(urls);
resourceBundle = ResourceBundle.getBundle(fileName, Locale.getDefault(), loader);
}
return resourceBundle;
}
And this is how am invoking ResourceBundle
object:
ResourceBundle locationBundle = null;
try {
locationBundle = ReadPropertyUtil.getResourceBundle(propFileName);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Please guide whats wrong with this code and whats the correct way of reading an external properties file.
Well, I figured out the error myself. I was appending the fileName to the directory location File file = new File("resource/"+fileName);
which was wrong.
All I had to do was to first get the present working directory name using
System.getProperties("user.dir") //this gives me the path of my current directory
and passing only the directory name to file object.
File file = new File("resource/");
And then load the bundle using the specified file name.
resourceBundle = ResourceBundle.getBundle(fileName, Locale.getDefault(), loader);
ResourceBundle automatically looks into the directory and loads the file specified by the fileName