如何使用配置文件
合理使用配置文件,可以避免把代码写死在java文件中,java文件生成class后部署在项目中更改起来就特别麻烦,所以使用配置文件,这样有可能修改的参数写在配置文件里面,就可以规避修改java文件了。
使用配置文件的步骤
1、首先要使用配置文件的工具类(如果不想重新写的话),以下是配置文件工具类ConfigProperties 源码:
package cn.swsk.sdp.core.comm;
import cn.swsk.sdp.utils.PropertiesHelper;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* 配置文件工具类
* Created by Conkis-tp on 2017/4/27.
*/
public class ConfigProperties {
private static Log logger = LogFactory.getLog(ConfigProperties.class);
public static final String DEF_SPLIT = "\\s*,\\s*";
//文件路径
private static String fileUrl = "conf/config.properties";
private static PropertiesHelper prop = null;
private static String fileUrl_active = null;
private static PropertiesHelper prop_active = null;
static {
InputStream fis = null;
try {
prop = new PropertiesHelper(fileUrl);
String activeModel = prop.getProperties("server.active");
if(activeModel != null && !activeModel.isEmpty()){
fileUrl_active = "conf/config_"+activeModel+".properties";
prop_active = new PropertiesHelper(fileUrl_active);
}
} catch (Exception e) {
logger.error("初始化加载配置文件对象时发生异常:" + e.toString());
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (Exception e) {
}
}
}
/**
* 通过键获取值
*
* @param key
* @return
*/
public static String getProperties(String key) {
if(prop_active != null){
if(prop_active.getProperties(key) != null && !prop_active.getProperties(key).isEmpty()){
return prop_active.getProperties(key);
}
}
return prop.getProperties(key);
}
public static String getString(String propertyName) {
return getString(propertyName, null);
}
public static String getString(String propertyName, String defaultValue) {
String value = getProperties(propertyName);
if (value == null || "".equals(value.trim())) {
return defaultValue;
}
return value.trim();
}
public static Boolean getBoolean(String propertyName) {
return getBoolean(propertyName, null);
}
public static Boolean getBoolean(String propertyName, Boolean defaultValue) {
String value = getProperties(propertyName);
if (value == null || "".equals(value.trim())) {
return defaultValue;
}
return toBoolean(propertyName, value);
}
public static Long getLong(String propertyName) {
return getLong(propertyName, null);
}
public static Long getLong(String propertyName, Long defaultValue) {
String value = getProperties(propertyName);
if (value == null || "".equals(value.trim())) {
return defaultValue;
}
try {
return Long.valueOf(value.trim());
} catch (NumberFormatException e) {
return defaultValue;
}
}
public static Integer getInteger(String propertyName) {
return getInteger(propertyName, null);
}
public static Integer getInteger(String propertyName, Integer defaultValue) {
String value = getProperties(propertyName);
if (value == null || "".equals(value.trim())) {
return defaultValue;
}
try {
return Integer.valueOf(value.trim());
} catch (NumberFormatException e) {
return defaultValue;
}
}
public static Float getFloat(String propertyName) {
return getFloat(propertyName, null);
}
public static Float getFloat(String propertyName, Float defaultValue) {
String value = getProperties(propertyName);
if (value == null || "".equals(value.trim())) {
return defaultValue;
}
try {
return Float.valueOf(value.trim());
} catch (NumberFormatException e) {
return defaultValue;
}
}
public static Double getDouble(String propertyName) {
return getDouble(propertyName, null);
}
public static Double getDouble(String propertyName, Double defaultValue) {
String value = getProperties(propertyName);
if (value == null || "".equals(value.trim())) {
return defaultValue;
}
try {
return Double.valueOf(value.trim());
} catch (NumberFormatException e) {
return defaultValue;
}
}
public static List<String> getStringList(String propertyName) {
return getStringList(propertyName, DEF_SPLIT, null);
}
public static List<String> getStringList(String propertyName, String split) {
return getStringList(propertyName, split, null);
}
public static List<String> getStringList(String propertyName, String split, String defaultValue) {
String value = getString(propertyName, defaultValue);
if (value == null)
return Collections.EMPTY_LIST;
String[] props = value.split(split);
if (props.length == 0)
return Collections.EMPTY_LIST;
List<String> valList = new ArrayList<>(props.length);
for (String val : props) {
if (!(val == null || val.isEmpty()))
valList.add(val);
}
return valList;
}
public static String[] getStringArray(String key) {
return getStringArray(key, DEF_SPLIT, null);
}
public static String[] getStringArray(String key, String split) {
return getStringArray(key, split, null);
}
public static String[] getStringArray(String key, String split, String def) {
String val = getString(key, def);
return val == null ? new String[0] : val.split(split);
}
public static List<Double> getDoubleList(String propertyName) {
return getDoubleList(propertyName, DEF_SPLIT, null);
}
public static List<Double> getDoubleList(String propertyName, String split) {
return getDoubleList(propertyName, split, null);
}
public static List<Double> getDoubleList(String propertyName, String split, String defaultValue) {
String value = getString(propertyName, defaultValue);
if (value == null)
return Collections.EMPTY_LIST;
String[] props = value.split(split);
if (props.length == 0)
return Collections.EMPTY_LIST;
List<Double> valList = new ArrayList<>(props.length);
for (String val : props) {
try {
valList.add(Double.parseDouble(val));
} catch (Exception e) {
//ignore;
}
}
return valList;
}
public static double[] getDoubleArray(String key) {
return getDoubleArray(key, DEF_SPLIT, null);
}
public static double[] getDoubleArray(String key, String split) {
return getDoubleArray(key, split, null);
}
public static double[] getDoubleArray(String key, String split, String def) {
List<Double> dList = getDoubleList(key, split, def);
double[] d = new double[dList.size()];
for (int i = 0, l = dList.size(); i < l; i++)
d[i] = dList.get(i);
return d;
}
public static List<Integer> getIntegerList(String propertyName) {
return getIntegerList(propertyName, DEF_SPLIT, null);
}
public static List<Integer> getIntegerList(String propertyName, String split) {
return getIntegerList(propertyName, split, null);
}
public static List<Integer> getIntegerList(String propertyName, String split, String defaultValue) {
String value = getString(propertyName, defaultValue);
if (value == null)
return Collections.EMPTY_LIST;
String[] props = value.split(split);
if (props.length == 0)
return Collections.EMPTY_LIST;
List<Integer> valList = new ArrayList<>(props.length);
for (String val : props) {
try {
valList.add(Integer.parseInt(val));
} catch (Exception e) {
//ignore;
}
}
return valList;
}
public static int[] getIntArray(String key) {
return getIntArray(key, DEF_SPLIT, null);
}
public static int[] getIntArray(String key, String split) {
return getIntArray(key, split, null);
}
public static int[] getIntArray(String key, String split, String def) {
List<Integer> dList = getIntegerList(key, split, def);
int[] d = new int[dList.size()];
for (int i = 0, l = dList.size(); i < l; i++)
d[i] = dList.get(i);
return d;
}
public static List<Float> getFloatList(String propertyName) {
return getFloatList(propertyName, DEF_SPLIT, null);
}
public static List<Float> getFloatList(String propertyName, String split) {
return getFloatList(propertyName, split, null);
}
public static List<Float> getFloatList(String propertyName, String split, String defaultValue) {
String value = getString(propertyName, defaultValue);
if (value == null)
return Collections.EMPTY_LIST;
String[] props = value.split(split);
if (props.length == 0)
return Collections.EMPTY_LIST;
List<Float> valList = new ArrayList<>(props.length);
for (String val : props) {
try {
valList.add(Float.parseFloat(val));
} catch (Exception e) {
//ignore;
}
}
return valList;
}
public static float[] getFloatArray(String key) {
return getFloatArray(key, DEF_SPLIT, null);
}
public static float[] getFloatArray(String key, String split) {
return getFloatArray(key, split, null);
}
public static float[] getFloatArray(String key, String split, String def) {
List<Float> dList = getFloatList(key, split, def);
float[] d = new float[dList.size()];
for (int i = 0, l = dList.size(); i < l; i++)
d[i] = dList.get(i);
return d;
}
public static boolean isNotEmpty(String propKey) {
String propValue = getProperties(propKey);
return propValue != null && propValue.length() > 0;
}
private static Boolean toBoolean(String propertyName, String value) {
value = value.trim();
if ("true".equalsIgnoreCase(value) || "on".equalsIgnoreCase(value)
|| "yes".equalsIgnoreCase(value) || "ok".equalsIgnoreCase(value)
|| "1".equalsIgnoreCase(value)) {
return new Boolean(true);
} else {
return new Boolean(false);
}
}
}
2、其中还是用到了PropertiesHelper的工具类,源码如下:
package cn.swsk.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* 配置文件读取和写入工具类
* @author Jacky.Jiang
*
*/
public class PropertiesHelper {
private static Log logger = LogFactory.getLog(PropertiesHelper.class);
private String project_root = "";
private File file = null;
public PropertiesHelper(String filePath) {
try {
//构造时获取到项目的物理根目录
project_root = getResourcePath();
//处理路径中存在中文或空格时错误
project_root = java.net.URLDecoder.decode(project_root,"utf-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
if(filePath != null && filePath.length() > 0){
try {
file = new File(project_root + filePath);
} catch (Exception e) {
logger.error(e);
}
}
}
/**
* 通过键获取值
* @param key
* @return
*/
public String getProperties(String key){
InputStream fis = null;
try {
Properties prop = new Properties();
fis = new FileInputStream(getAbsolutePath());
prop.load(fis);
return prop.getProperty(key);
} catch (Exception e) {
logger.error(e);
}finally{
try{if(fis != null){fis.close();}}catch(Exception e){}
}
return "";
}
/**
* 追加参数
* @param key
* @param value
* @throws Exception
*/
public void setProperties(String key,String value)throws Exception{
Properties prop = new Properties();
FileOutputStream outputFile = null;
InputStream fis = null;
try {
//输入流和输出流要分开处理, 放一起会造成写入时覆盖以前的属性
fis = new FileInputStream(getAbsolutePath());
//先载入已经有的属性文件
prop.load(fis);
//追加新的属性
prop.setProperty(key, value);
//写入属性
outputFile = new FileOutputStream(getAbsolutePath());
prop.store(outputFile, "");
outputFile.flush();
} catch (Exception e) {
logger.error(e);
throw e;
}finally{
try{if(fis != null){fis.close();}}catch(Exception e){}
try{if(outputFile != null){outputFile.close();}}catch(Exception e){}
}
}
/**
* 获取文件绝对路径
* @return
*/
public String getAbsolutePath(){
try {
return file.getAbsolutePath();
} catch (Exception e) {
logger.error(e);
}
return "";
}
/**
* 获取资源文件根目录
* @return
*/
public String getResourcePath(){
try {
return Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath();
} catch (URISyntaxException e) {
e.printStackTrace();
return "";
}
}
}
3、由于该项目是分开两个平台,等于说他们使用的用户是同一批(数据库都是同一个),但是通过配置文件的修改参数,前端页面就会进入两个系统,简单的说就是把菜单分开在两个平台展示,利用配置文件做权限的区分,在客户看来这就是两个不同的系统,但是在我们开发人员来说就是菜单权限区分,换换背景、换换logo。
在配置文件工具类里需要注意的地方是,由于项目中有三个配置文件:config.properties、config_dev.properties、config_prod.propertis。
config.properties这个配置文件是公用的,两个系统都能使用的,在这个配置文件里面,有个server.active的简直,通过这个简直判断读取不同的配置文件
String activeModel = prop.getProperties("server.active");
if(activeModel != null && !activeModel.isEmpty()){
fileUrl_active = "conf/config_"+activeModel+".properties";
prop_active = new PropertiesHelper(fileUrl_active);
config.properties这个配置文件里面只要做好读取选择就好了,把另一个系统的配置文件注释掉就好了:
server.active=dev
#server.active=prod
4、使用工具类里面的getProperties方法可以直接从键值获取后面的参数:
String useMangar = ConfigProperties.getProperties("menu.userManger");
配置文件中:
menu.userManger = all