java操作properties配置文件
Java中有个类Properties(Java.util.Properties),主要用于读取Java的配置文件,将一些可能需要变化的值存放在properties中进行配置,通常为为.properties文件,其实就是普通的文本文件,文件的内容的格式是“键=值”的格式,文本注释信息可以用"#"来注释。尽量使用UTF-8格式存储。jdk自身提供的类有缺点,所以我们通常使用 commons-configuration框架进行解析。
1.1.1. Properties类图
1.1.2. 读取Properties配置文件比较常用的方式
1。使用java.lang.Class类的getResourceAsStream(String name)方法
InputStream in = getClass().getResourceAsStream("文件名称");
2.使用流的方式操作
InputStream in = new BufferedInputStream(new FileInputStream(filepath));
1.1.3. 缺点
1.格式必须是k=v 不能有空格。
2.不能定时刷新变化的值(比如线上环境修改值程序读取到的还是旧值)。需要自己写程序控制。
3.值都是string类型需要自己获取的时候根据需求转换。
基于上面的缺点我们可以使用org.apache.commons.configuration类解决下面是日常开发中读取properties封装。
1.1.4. commons-configuration框架的使用
1.1.4.1. maven包导入
<dependency>
<groupId>commons-configuration</groupId>
<artifactId>commons-configuration</artifactId>
<version>1.8</version>
</dependency>
1.1.4.2. 工具类封装
package cn.xhgg.common.configuration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 这个类型的配置,文件首先需要有配置文件,其次配置文件应该写入该类,再则配置文件的编码方式必须是UTF8
*/
public class PropertiesConfigUtil {
private static Logger log = LoggerFactory.getLogger(PropertiesConfigUtil.class);
public static final String PROPS_SUFFIX = ".properties";
private static Map<String, PropertiesConfiguration> configMap = new ConcurrentHashMap<String, PropertiesConfiguration>();
private static PropertiesConfiguration getConfig(String configName) {
//去除空格
configName = configName.trim();
//有后缀使用后缀 没后缀 添加后缀
String configSig = StringUtils.endsWith(configName, PROPS_SUFFIX) ? configName : configName+PROPS_SUFFIX;
if (configMap.containsKey(configSig)) {
return configMap.get(configSig);
}
PropertiesConfiguration config = null;
try {
config=new PropertiesConfiguration();
config.setEncoding("UTF-8");
config.load(configSig);
//默认五秒检查一次
config.setReloadingStrategy(new FileChangedReloadingStrategy());
config.setThrowExceptionOnMissing(true);
configMap.put(configSig, config);
} catch (ConfigurationException e) {
e.printStackTrace();
}
return config;
}
public static Map<String, String> getKeyValuePairs(String configSig) {
PropertiesConfiguration config = getConfig(configSig);
if (config == null) {
return null;
}
Iterator<String> iters = config.getKeys();
Map<String, String> retMap = new HashMap<String, String>();
while (iters.hasNext()) {
String beforeKey = iters.next();
if (retMap.containsKey(beforeKey)) {
log.warn(configSig + " configKey:" + beforeKey + " repeated!!");
}
retMap.put(beforeKey, config.getString(beforeKey));
}
return retMap;
}
/**
* 通过PropertiesConfiguration取得参数的方法
* <p>
*
* @return 。
*/
static public String getString(String configSig, String key) {
return getConfig(configSig).getString(key);
}
static public String getString(String configSig, String key, String defaultValue) {
return getConfig(configSig).getString(key, defaultValue);
}
static public int getInt(String configSig, String key) {
return getConfig(configSig).getInt(key);
}
static public int getInt(String configSig, String key, int defaultValue) {
return getConfig(configSig).getInt(key, defaultValue);
}
static public boolean getBoolean(String configSig, String key) {
return getConfig(configSig).getBoolean(key);
}
static public boolean getBoolean(String configSig, String key, boolean defaultValue) {
return getConfig(configSig).getBoolean(key, defaultValue);
}
static public double getDouble(String configSig, String key) {
return getConfig(configSig).getDouble(key);
}
static public double getDouble(String configSig, String key, double defaultValue) {
return getConfig(configSig).getDouble(key, defaultValue);
}
static public float getFloat(String configSig, String key) {
return getConfig(configSig).getFloat(key);
}
static public float getFloat(String configSig, String key, float defaultValue) {
return getConfig(configSig).getFloat(key, defaultValue);
}
static public long getLong(String configSig, String key) {
return getConfig(configSig).getLong(key);
}
static public long getLong(String configSig, String key, long defaultValue) {
return getConfig(configSig).getLong(key, defaultValue);
}
static public short getShort(String configSig, String key) {
return getConfig(configSig).getShort(key);
}
static public short getShort(String configSig, String key, short defaultValue) {
return getConfig(configSig).getShort(key, defaultValue);
}
static public List<Object> getList(String configSig, String key) {
return getConfig(configSig).getList(key);
}
static public List<Object> getList(String configSig, String key, List<Object> defaultValue) {
return getConfig(configSig).getList(key, defaultValue);
}
static public byte getByte(String configSig, String key) {
return getConfig(configSig).getByte(key);
}
static public byte getByte(String configSig, String key, byte defaultValue) {
return getConfig(configSig).getByte(key, defaultValue);
}
static public String[] getStringArray(String configSig, String key) {
return getConfig(configSig).getStringArray(key);
}
}
1.1.4.3. 引入properties测试文件
rabbitmq.properties配置如下:
#rpc 模式rmq rpc.rabbit.host=l-opsdev3.ops.bj0.jd.com rpc.rabbit.port=5672 rpc.rabbit.username=jd_vrmphoto rpc.rabbit.password=jd_vrmphoto rpc.rabbit.vhost=jd/vrmphoto rpc.rabbit.queue=rpc_queue rpc.rabbit.exchange=photoworker rpc.rabbit.key=photoworker.rpc
1.1.4.4. 测试
PropertiesConfigUtil config=new PropertiesConfigUtil();
String username = config.getString("rabbitmq", "rpc.rabbit.username");
System.out.println(username);
输出结果:
jd_vrmphoto
ok,大功告成。
1.1.4.5. 注意事项
1.编码最好UTF-8统一。
ReloadingStrategy策略选择。可以看具体的实现类和使用场景。我用的一般是FileChangedReloadingStrategy类。
java操作properties配置文件的更多相关文章
- Java 读写Properties配置文件
Java 读写Properties配置文件 JAVA操作properties文件 1.Properties类与Properties配置文件 Properties类继承自Hashtable类并且实现了M ...
- java读取properties配置文件总结
java读取properties配置文件总结 在日常项目开发和学习中,我们不免会经常用到.propeties配置文件,例如数据库c3p0连接池的配置等.而我们经常读取配置文件的方法有以下两种: (1) ...
- Java读取Properties配置文件
1.Properties类与Properties配置文件 Properties类继承自Hashtable类并且实现了Map接口,使用键值对的形式来保存属性集.不过Properties的键和值都是字符串 ...
- 【转】Java 读写Properties配置文件
[转]Java 读写Properties配置文件 1.Properties类与Properties配置文件 Properties类继承自Hashtable类并且实现了Map接口,也是使用一种键值对的形 ...
- java读取properties配置文件信息
一.Java Properties类 Java中有个比较重要的类Properties(Java.util.Properties),主要用于读取Java的配置文件,各种语言都有自己所支持的配置文件,配置 ...
- JAVA操作properties文件
va中的properties文件是一种配置文件,主要用于表达配置信息,文件类型为*.properties,格式为文本文件,文件的内容是格式是"键=值"的格式,在properties ...
- Java 读取 .properties 配置文件的几种方式
Java 开发中,需要将一些易变的配置参数放置再 XML 配置文件或者 properties 配置文件中.然而 XML 配置文件需要通过 DOM 或 SAX 方式解析,而读取 properties 配 ...
- java读取.properties配置文件的几种方法
读取.properties配置文件在实际的开发中使用的很多,总结了一下,有以下几种方法(仅仅是我知道的):一.通过jdk提供的java.util.Properties类.此类继承自java.util. ...
- Java读取properties配置文件经常用法
在开发中对properties文件的操作还是蛮常常的.所以总结了几种操作方法,为后面的开发能够进行參考. 1.通过java.util.ResourceBundle类来读取 这边測试用到了枚举类进行传入 ...
随机推荐
- Codeforces Round#402(Div.1)掉分记+题解
哎,今天第一次打div1 感觉头脑很不清醒... 看到第一题就蒙了,想了好久,怎么乱dp,倒过来插之类的...突然发现不就是一道sb二分吗.....sb二分看了二十分钟........ 然后第二题看了 ...
- 【转载】 HTTP 中 GET 与 POST 的区别
HTTP 中 GET 与 POST 的区别 GET和POST是HTTP请求的两种基本方法,要说它们的区别,接触过WEB开发的人都能说出一二. 最直观的区别就是GET把参数包含在URL中,POST通 ...
- MySQl之最全且必会的sql语句
创建一个名称为mydb1的数据库,如果有mydb1数据库则直接使用,如果无则创建mydb1数据库 create database if not exists mydb1; create databas ...
- iOS 搜索记录
需求描述: 使用单独的搜索界面, 提供用户进行搜索并留下搜索记录. 搜索记录可以提供用户进行再次搜索, 或者把搜索记录清空. 方案和技术点: 存储方式使用 NSUserDefaults, 把对应的字段 ...
- openwrt 下添加sim760ce usb驱动
SIM7500_SIM7600 系列模块的 USB VID 是 0x1E0E PID 是 0x9001. 作为 Slave USB 设备,配置如下表 USB 接口波特率自适应 9600.115200 ...
- 解决 APPARENT DEADLOCK!!! Creating emergency threads for unassigned pending tas
报错信息:APPARENT DEADLOCK!!! Creating emergency threads for unassigned pending tasks! 在网上查了一下,大部分网友分析是c ...
- Jackson工具
Jackson Jackson包含一个core JAR,和两个依赖core JAR的JAR: jackson-core-2.2.3.jar(核心jar包,下载地址) jackson-annotatio ...
- 两个对象用equals方法比较为true,它们的Hashcode值相同吗?
两个对象用equals方法比较为true,它们的Hashcode值相同吗? 答:不一定相同.正常情况下,因为equals()方法比较的就是对象在内存中的值,如果值相同,那么Hashcode值也应该相同 ...
- Python小代码_1_九九乘法表
Python小代码_1_九九乘法表 max_num = 9 row = 1 while row <= max_num: col = 1 while col <= row: print(st ...
- jupyter notebook 更换主题的方法
参考 https://github.com/dunovank/jupyter-themes install with pip # install jupyterthemes pip install j ...