Load properties from outside the classpath

 

 Problem:

You want to locate your resource bundles outside your application classpath.

Solution:

Create an InputStream and use it to create the PropertyResourceBundle directly using the constructor.

To loop through a collection of locales and look for a matching properties file outside the classpath then extract a resource from it:

try {
   //Create an arra of locale ids.  This should be created programmaticaly
    String[] localeChain = {"fr_CA","fr","en_CA","en"};
    //Get the root directory you will locate the resources in
    File directory = new File("C:\\temp\\");
    //Get a List of files contained in the director.  We could use a FileFilter to
    //reduce this list
    List<String> files = Arrays.asList(directory.list());
    //The InputStream will be used to load the properties file.  Here we initialize as null;
    InputStream is = null;
    //Loop through the locales in the chain
    for(int x = 0; x < localeChain.length; x++) {
        //Check if a properties file exists for that locale.
        //Naturally in a real usage the file name would be specified programmaticaly.
        //If a match is found we create the InputStream and break out of the loop
        String fileName = "foo_"+localeChain[x]+".prop";
        if(files.contains(fileName)){
            is = new FileInputStream(new File(directory,fileName));
            break;
        }
    }
    //If the InputStream is still null look for a root file
    if(is == null && files.contains("foo.prop") ) {
        is = new FileInputStream(new File(directory,"foo.prop"));
    }
    //If a file has been found create the ResourceBundle and output some text
    if(is != null) {
        PropertyResourceBundle rb2 = new PropertyResourceBundle(is);
        System.out.println(rb2.getString("foo"));
    }
}
catch (MalformedURLException e) {
    e.printStackTrace();
}
catch (IOException e) {
    e.printStackTrace();
}