0

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.

almightyGOSU
  • 3,731
  • 6
  • 31
  • 41
roger_that
  • 9,493
  • 18
  • 66
  • 102
  • possible duplicate of [Loading resources using getClass().getResource()](http://stackoverflow.com/questions/2343187/loading-resources-using-getclass-getresource) – CMPS Jul 01 '14 at 06:23

2 Answers2

2
  1. Get Jar file path.
  2. Get Parent folder of that file.
  3. Use that path in InputStreamPath with your properties file name.

    Properties prop = new Properties();
    try {
            File jarPath=new File(YourClassNameInJar.class.getProtectionDomain().getCodeSource().getLocation().getPath());
            String propertiesPath=jarPath.getParentFile().getAbsolutePath();
            System.out.println(" propertiesPath-"+propertiesPath);
            prop.load(new FileInputStream(propertiesPath+"/resource/locations.properties"));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    
Ninad Pingale
  • 6,801
  • 5
  • 32
  • 55
2

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

Grodriguez
  • 21,501
  • 10
  • 63
  • 107
roger_that
  • 9,493
  • 18
  • 66
  • 102