如何去读properties结尾的文件,方便程序的灵活配置参数
首先建立`PropertiesReader类一般放在util包下面
public class PropertiesReader {
/**
* 读取配置文件
*/
private Properties getProperties(){
Properties p = null;
try{
// 读取url配置文件configuration.properties为具体配置文件的名字
InputStream in = this.getClass().getClassLoader().getResourceAsStream("configuration.properties");
p = new Properties();
p.load(in);
}catch (Exception e){
System.out.println("====读取异常====="+e.getMessage());
p = null;
}
return p;
}
/**
* 查询配置文件中指定参数对应的值
*/
public static String getProperty(String propertyName){
PropertiesReader reader = new PropertiesReader();
Properties p = reader.getProperties();
if(null == p)
return null;
String result = p.getProperty(propertyName);
return result;
}
configuration.properties具体如下
项目引入参数
props.put("bootstrap.servers",PropertiesReader.getProperty("product_IP"));
PropertiesReader.getProperty("product_IP")
即可灵活引入参数,方便配置
加载外部文件目录下的配置
添加filepath
private static Logger logger = Logger.getLogger("FilePath");
//读取文件路径 在项目文件的上一次conf文件夹里面
public static String getConfFileDir(){
String path = System.getProperty("user.dir")+File.separator+".."+File.separator + "conf";
return path;
}
public static String getConfFile(String fileNamePath){
String path = getConfFileDir() + File.separator + fileNamePath;
judeFileExists(new File(path));
return path;
}
// 判断文件是否存在
public static void judeFileExists(File file) {
if (file.exists()) {
return;
} else {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
在ConstantUti修改
// 配置文件名称
public static final String PROPERTIES_PATH = FilePath.getConfFile("外部文件目录");
PropertiesReader
private Properties getProperties(){
Properties pps = null;
try{
// 读取url配置文件
InputStream in = new FileInputStream(ConstantUtil.PROPERTIES_PATH);
pps = new Properties();
pps.load(in);
}catch (Exception e){
e.printStackTrace();
System.out.println("===========读取配置文件异常========="+e.getMessage());
pps = null;
}
return pps;
}
/**
* 查询配置文件中指定参数对应的值
* @param propertyName 参数名称
*/
public static String getProperty(String propertyName){
PropertiesReader reader = new PropertiesReader();
Properties pps = reader.getProperties();
if(null == pps)
return null;
String result = pps.getProperty(propertyName);
return result;
}
其他一切照旧即可