25
Mar

Utility to load all properties files, located in a specified folder

Following code snippet demonstrates, how to load all property files into memory:
———————————————————————————

Pre-requisite:
—————
There exists a folder on local file system which contains files with extension “PROPERTIES”

Functions to implement Property reader:
—————————————

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ObjectRepository {
private static final Logger LOGGER = LoggerFactory.getLogger(ObjectRepository.class);

private static Properties props = new Properties();
private static boolean isLoaded = false;

private static String objectRepositoryDirectory;

public static void setRepositoryDirectory(String objectRepositoryDir) {
objectRepositoryDirectory = objectRepositoryDir;
}

/**
* Load all locator files
*
* @returns – Properties containing all elements defined in properties file
*/

public static Properties initialize() throws IOException {
if (!isLoaded) {
File objRepositoryDir = new File(objectRepositoryDirectory);

File[] locatorFiles = objRepositoryDir.listFiles();
for (File f : locatorFiles) {
if (f.getName().endsWith(“.properties”) || f.getName().endsWith(“.PROPERTIES”)) {
LOGGER.info(“Loading locator file: ” + f.getName());

try {
props.load(new FileInputStream(f));
} catch (IOException e) {
throw new IOException(“Unable to load properties file ” + f.getName() + “!”);
}
}

isLoaded = true;
}
}

return props;
}

/* One of the way to initialize all property files */

public static void main(String[] args) throws IOException {
String objectRepositoryDirectory = “C:\\SRTemp\\temp\\properties”;
setRepositoryDirectory(objectRepositoryDirectory);

Properties obj = initialize();
if (isLoaded) {
System.out.println(obj.getProperty(“name”));
System.out.println(obj.getProperty(“lname”));
}
}
}

Output:
———

19:31:50.669 [main] INFO com.allstate.utilities.ObjectRepository – Loading locator file: first.properties
19:31:50.675 [main] INFO com.allstate.utilities.ObjectRepository – Loading locator file: second.PROPERTIES
name’s value
lname’s value