可以使用key和文件名的组合获取value
工具类1
package dsf.atest.test;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public class PropertiesUtil {
private static ResourceLoader loader = ResourceLoader.getInstance();
private static ConcurrentMap<String, String> configMap = new ConcurrentHashMap<String, String>();
private static final String DEFAULT_CONFIG_FILE = "test.properties";
private static Properties prop = null;
public static String getStringByKey(String key, String propName) {
try {
prop = loader.getPropFromProperties(propName);
} catch (Exception e) {
throw new RuntimeException(e);
}
key = key.trim();
if (!configMap.containsKey(key)) {
if (prop.getProperty(key) != null) {
configMap.put(key, prop.getProperty(key));
}
}
return configMap.get(key);
}
public static String getStringByKey(String key) {
return getStringByKey(key, DEFAULT_CONFIG_FILE);
}
public static Properties getProperties() {
try {
return loader.getPropFromProperties(DEFAULT_CONFIG_FILE);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
工具类2
package dsf.atest.test;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public final class ResourceLoader {
private static ResourceLoader loader = new ResourceLoader();
private static Map<String, Properties> loaderMap = new HashMap<String, Properties>();
private ResourceLoader() {
}
public static ResourceLoader getInstance() {
return loader;
}
public Properties getPropFromProperties(String fileName) throws Exception {
Properties prop = loaderMap.get(fileName);
if (prop != null) {
return prop;
}
String filePath = null;
String configPath = System.getProperty("configurePath");
if (configPath == null) {
filePath = this.getClass().getClassLoader().getResource(fileName).getPath();
} else {
filePath = configPath + "/" + fileName;
}
prop = new Properties();
prop.load(new FileInputStream(new File(filePath)));
loaderMap.put(fileName, prop);
return prop;
}
}
获取实例
public static void main(String[] args) {
String name = PropertiesUtil.getStringByKey("city", "wordBook.properties");
System.out.println(name.split(",")[name.split(",").length-1]);
}
验证通过,何以运行