properties工具类

包含读取参数、读取全部参数返回一个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;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值