Java代码
public static void reloadProperties() {
//Get a list of files loaded
ArrayList
//Cycle through list and reload all files
for (int icnt =0;icnt < files.size();icnt++) {
loadPropertiesFile(files.get(icnt),true);
}
}
public static boolean loadPropertiesFile(String filename, boolean reload) {
//If property file is already loaded and reload is required then remove it from the loaded file list.
if (propfiles.containsKey(filename)) {
if (!reload) return true;
propfiles.remove(filename);
}
try {
//Find the property file on the class path and load it.
System.out.println("Loading properties file: "+filename);
ClassLoader loader = Thread.currentThread().getContextClassLoader();
InputStream is = loader.getResourceAsStream(filename);
Properties props = new Properties();
props.load(is);
//Add it to the hashtable
propfiles.put(filename,props);
return true;
}
catch (Exception e) {
System.out.println("Failed to load properties file: "+e.getMessage());
return false;
}
}
/**
* getFileList - returns a sorted list of property file names that have been loaded
*/
public static ArrayList
//Get empty list
ArrayList
//Cycle through property files hash table and add names to the return list
Set
Iterator it = keys.iterator();
while (it.hasNext()) {
files.add((String) it.next());
}
//Sort list
Collections.sort(files);
return files;
}
public static String getValue(String propertiesFile,String key) {
// If property file is not load it then load it now
if (!propfiles.containsKey(propertiesFile)) {
if (!loadPropertiesFile(propertiesFile,true)) {
throw new RuntimeException("Failed to load properties file: "+propertiesFile);
}
}
//Get the property file from the hashmap
Properties props = propfiles.get(propertiesFile);
//Return the property value
try {
System.out.println("Getting properties: "+key);
return props.getProperty(key);
}
catch (Exception e) {
System.out.println("Failed to find property in file");
throw new RuntimeException("Failed to find property");
}
}
public static void main(String[] args) {
String value=getValue("my.properties","key1");
System.out.println("Printing Value:" + value);
reloadProperties();
value=getValue("my.properties","key1");
System.out.println("Printing Value:" + value);
}
本文出自“持续疯长,往天那边去”