Search This Blog

Wednesday, June 23, 2010

Loading resources from classpath


The following java code snippet can be used to load all resources with “.properties” as extension under path specified in “resourceLoc”. The getDotReplaced() method will replace the ‘\’ or ‘/’ to ‘.’ Which the ResourceBundle requires for loading the resource.

try {

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if(classLoader == null){
classLoader = getClass().getClassLoader();                     
}
Enumeration resPaths = classLoader.getResources(resourceLoc);
String loc = getDotReplaced(resourceLoc);
while(resPaths.hasMoreElements()) {
     
InputStream inputStream =  resPaths.nextElement().openStream();
                       
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String fileName;
      while((fileName = reader.readLine()) != null) {
            fileName = fileName.trim();
            if(fileName.length() == 0) {
                  continue; //blank line ignored
            }
                             
            if(isProperties(fileName))
            {
            String bundleKey = getBundleKey(fileName);
            if(bundleKey!=null)
            {
                  ResourceBundle resourceBundle = ResourceBundle.getBundle(loc+"."+bundleKey,locale);
            }
      }
}
}                      
} catch (Exception exep) {
                  LOGGER.error(exep.getMessage(), exep);
}


and the code for getDotReplaced() is as follows,

private String getDotReplaced(String resourceLoc) {
String loc = null;
      loc = resourceLoc.replace('\\', '/');
      loc = resourceLoc.replace('/', '.');
      return loc;
}
isProperties(fileName) checks whether the file is a property file.
private boolean isProperties(String fileName) {
int index = fileName.indexOf(PROPERTYFILE);
      if (index > 0) {
            return true;
      }
      return false;
}

No comments:

Post a Comment