包含读取参数、读取全部参数返回一个map、修改/写入新的参数、获取文件路径的方法
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* 传入key获取common.properties中的参数
*
*/
public class PropertiesUtils {
/**
* 获取配置文件参数
* @param key
* @return value 没有参数值则返回空字符串
*/
public static String get(String key){
ClassLoader cl = Thread.currentThread().getContextClassLoader();
java.io.InputStream io = cl.getResourceAsStream("common.properties");
Properties p = new Properties();
try {
p.load(io);
return p.getProperty(key, "");
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
/**
* 获取properties文件中的所有参数,以map形式返回
* @param propertiesFile properties文件名
* @return map
*/
public static Map<String,String> getAllParamFromProperties(String propertiesFile){
Map<String,String> paramMap = new HashMap<String,String>();
ClassLoader cl = Thread.currentThread().getContextClassLoader();
java.io.InputStream io = cl.getResourceAsStream(propertiesFile);
InputStream in = new BufferedInputStream(io);
Properties p = new Properties();
try {
p.load(in);
Enumeration en = p.propertyNames();
while (en.hasMoreElements()) {
String strKey = (String) en.nextElement();
String strValue = p.getProperty(strKey);
paramMap.put(strKey, strValue);
}
} catch (IOException e) {
e.printStackTrace();
}
return paramMap;
}
/**
* 添加/修改properties中的参数
* @param propertiesFile
* properties文件名
* @param key
* 参数名
* @param value
* 参数值
* @throws IOException
*/
public static void writeProperties(String propertiesFile,String key,String value) throws IOException {
String filePath = getFilePath(propertiesFile);
Properties pps = new Properties();
InputStream in = new FileInputStream(filePath);
pps.load(in);
OutputStream out = new FileOutputStream(filePath);
pps.setProperty(key, value);
pps.store(out, "Update " + key + " name");
}
/**
* 获取properties路径,返回文件路径或空字符串
* @param fileName
* 文件名,如log4j.properties
* @return
* 返回文件路径或""
*/
public static String getFilePath(String fileName){
ClassLoader cl = Thread.currentThread().getContextClassLoader();
String path = cl.getResource(fileName).getPath();
return path;
}
}