Java中获取包含变量的配置文件config.properties内容

时间:2022-05-22 14:33:37

应用场景

有些时候项目中会用到很多路径,并且很可能多个路径在同一个根目录下,那为了方便配置的修改,达到只修改根目录即可达到一改全改的效果,此时就会想到要是有变量就好了;

另外有时候路径中的文件名是不确定的,要靠业务程序运行时去判断文件名应该如何设置,而又希望此文件下的目录名是确定的,那此时用变量也是比较好的解决方式。

示例代码

config.properties 如下

#根目录
root_path = D:/myroot #用户目录
users_path = ${root_path}/users #用户相册目录
pictures_path = ${users_path}/{username}/pictures/{year}/{month}/{date} #用户文件目录
files_path = ${users_path}/{username}/files/{year}/{month}/{date} #系统日志文件
logs_path = ${root_path}/logs

说明:${root_path}形式的作为配置文件中路径变量;{year}形式的作为运行时替换的字段。

PropertiesUtil 工具类如下,用于配置文件值和转化变量

package com.tz.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern; /**
*
* @author tianzhen
*
*/
public enum PropertiesUtil { ROOT_PATH("root_path"),
USERS_PATH("users_path"),
PICTURES_PATH("pictures_path"),
FILES_PATH("files_path"),
LOGS_PATH("logs_path"); private String title;
private static Properties props;
private PropertiesUtil(String title){
this.title = title;
} private static final String PROPERTIES = "config.properties"; private static final Pattern PATTERN = Pattern.compile("\\$\\{([^\\}]+)\\}"); static{
try {
props = new Properties();
InputStream ins = PropertiesUtil.class.getClassLoader().getResourceAsStream(PROPERTIES);
props.load(ins);
ins.close();
} catch (IOException e) {
e.printStackTrace();
}
} private String getTitle() {
return title;
} public static String getTranslate(PropertiesUtil prop, Map<String, String> params){
String path = get(prop);
if(path==null||path.equals("")){
return "";
}
if(params!=null && !params.keySet().isEmpty()){
//需要替换的字段均放入map中,包括需要替换的日期
for(String key : params.keySet()){
path = path.replace("{"+key+"}", params.get(key));
}
} //如不指定日期,则替换为当前日期
Calendar cal = Calendar.getInstance();
path = path.replace("{year}", cal.get(Calendar.YEAR)+"")
.replace("{month}", cal.get(Calendar.MONTH)+1>9?cal.get(Calendar.MONTH)+1+"":"0"+(cal.get(Calendar.MONTH)+1))
.replace("{date}", cal.get(Calendar.DATE)>9?cal.get(Calendar.DATE)+"":"0"+cal.get(Calendar.DATE)); return path;
} public static String get(PropertiesUtil prop){
String value = props.getProperty(prop.getTitle());
return value==null?null:loop(value);
} @SuppressWarnings("static-access")
private static String loop(String key){
//定义matcher匹配其中的路径变量
Matcher matcher = PATTERN.matcher(key);
StringBuffer buffer = new StringBuffer();
boolean flag = false;
while (matcher.find()) {
String matcherKey = matcher.group(1);//依次替换匹配到的路径变量
String matchervalue = props.getProperty(matcherKey);
if (matchervalue != null) {
matcher.appendReplacement(buffer, matcher.quoteReplacement(matchervalue));//quoteReplacement方法对字符串中特殊字符进行转化
flag = true;
}
}
matcher.appendTail(buffer);
//flag为false时说明已经匹配不到路径变量,则不需要再递归查找
return flag?loop(buffer.toString()):key;
} }

测试代码如下

package com.tz.test;

import java.util.HashMap;
import java.util.Map; import com.tz.util.PropertiesUtil; public class Test { public static void main(String[] args) {
System.out.println("********无参取路径***********");
System.out.println(" [root_path] "+PropertiesUtil.get(PropertiesUtil.ROOT_PATH));
System.out.println(" [users_path] "+PropertiesUtil.get(PropertiesUtil.USERS_PATH));
System.out.println("[pictures_path] "+PropertiesUtil.get(PropertiesUtil.PICTURES_PATH));
System.out.println(" [files_path] "+PropertiesUtil.get(PropertiesUtil.FILES_PATH));
System.out.println(" [logs_path] "+PropertiesUtil.get(PropertiesUtil.LOGS_PATH)); System.out.println("\n********无参转化取路径***********");
System.out.println(" [root_path] "+PropertiesUtil.getTranslate(PropertiesUtil.ROOT_PATH , null));
System.out.println(" [users_path] "+PropertiesUtil.getTranslate(PropertiesUtil.USERS_PATH, null));
System.out.println("[pictures_path] "+PropertiesUtil.getTranslate(PropertiesUtil.PICTURES_PATH, null));
System.out.println(" [files_path] "+PropertiesUtil.getTranslate(PropertiesUtil.FILES_PATH, null));
System.out.println(" [logs_path] "+PropertiesUtil.getTranslate(PropertiesUtil.LOGS_PATH, null)); System.out.println("\n********带参转化取路径***********");
Map<String, String> map = new HashMap<String, String>();
map.put("username", "tianzhen");
map.put("year", "2017");
map.put("month", "01");
map.put("date", "02"); System.out.println(" [root_path] "+PropertiesUtil.getTranslate(PropertiesUtil.ROOT_PATH , map));
System.out.println(" [users_path] "+PropertiesUtil.getTranslate(PropertiesUtil.USERS_PATH, map));
System.out.println("[pictures_path] "+PropertiesUtil.getTranslate(PropertiesUtil.PICTURES_PATH, map));
System.out.println(" [files_path] "+PropertiesUtil.getTranslate(PropertiesUtil.FILES_PATH, map));
System.out.println(" [logs_path] "+PropertiesUtil.getTranslate(PropertiesUtil.LOGS_PATH, map));
} }

结果截图:

Java中获取包含变量的配置文件config.properties内容