今天写了一个类,用来加载当前项目下的所有的properties配置文件
项目文件结构及使用方式
结构
--resources
--order.properties
--product.properties
--kafka.properties
--zk.properties
简单的使用方式
String val = PropertyUtil.get("order.key");
String val = PropertyUtil.get("product.key");
String val = PropertyUtil.get("kafka.key");
String val = PropertyUtil.get("zk.key");
通过 文件名.key 的方式获取配置好的 value
以后再也不用再每个配置文件单独去加载获取里面的内容了,解放配置文件的使用。
如果是非web项目,也可以完成同样的功能,只需要把根目录指向 ‘user.dir’即可
具体代码如下
package xxx.framework.basic;
import java.io.*;
import java.util.*;
/**
* Created by ikong on 2016-06-28.
*/
public class PropertyUtil {
private static String fileExtension = ".properties";
private static Properties properties = null;
static {
init();
}
public static String get(String key) {
return properties.getProperty(key);
}
public static void init() {
properties = new Properties();
String path = PropertyUtil.class.getClassLoader().getResource("/").getPath();
File file = new File(path);
List<File> files = getPropFile(file);
Map<String, File> map = new HashMap<String, File>();
for (File item : files) {
String fileName = item.getName().replace(fileExtension, "");
map.put(fileName, item);//去重
System.out.println(item.getName());
try {
FileReader reader = new FileReader(item.getPath());
BufferedReader br = new BufferedReader(reader);
String line;
while ((line = br.readLine()) != null) {
int index = line.indexOf("=");
if (index < 0) {
continue;
}
String name = line.substring(0, index);
String val = line.substring(index + 1);
properties.put(fileName + "." + name, val);
}
br.close();
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static List<File> getPropFile(File file) {
List<File> list = new ArrayList<File>();
File[] files = file.listFiles();
for (File fileItem : files) {
if (fileItem.isDirectory()) {
List<File> items = getPropFile(fileItem);
list.addAll(items);
} else if (fileItem.getName().endsWith(fileExtension)) {
list.add(fileItem);
}
}
return list;
}
}