Monday, January 7, 2008

simple properties file management

Use when:
1. a majority of classes have to each load its own set of settings.
2. properties file is located in folder outside the default classpath
3. a generic solution is needed for loading configuration files that are independent of the filesystem


==========

  1. create a new Class and have it named "ResourceManager"
  2. turn the class into a singleton by hiding the constructor and give it a method named getInstance() that returns an instance of the class
  3. create a static method that will handle file loading. name this method "getResource()" and have it accept a Class object named "name" as a parameter and have it return a Properties object
  4. pass the "name" object appended with ".properties" to the ClassLoader.getResourceAsStream() method to load a Properties file as an InputStream
  5. create a new Properties object and call its "load()" method using the InputStream from step 4

==========
Sample ResourceManager:

public final class ResourceManager {
private static ResourceManager inst;
private static Logger logger = Logger.getLogger(ResourceManager.class);

private ResourceManager(){

}

public static synchronized ResourceManager getInstance(){
if (inst==null)
inst= new ResourceManager();
return inst;
}
public Object clone() throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
}

public Properties getResource(String name){
Properties r = new Properties();
try{
name=name.replace('.', '/');
r.load( ClassLoader.getSystemResourceAsStream(name+".properties") );
}catch(IOException e){
logger.error(e);
}
return r;
}
public Properties getResource(Class name){
return getResource(name.getName());
}
}



=========
The ResourceManager class does not have to be a singleton, but it gives the added bonus of being memory efficient because creating multiple instances of it is no longer necessary; it having only one usable method. It can also be modified so that file access is threaded, preventing any slowdown on particularly large files. But thats for another trick.

No comments: