读取.properties文件的流程操作!!!

读取配置文件。在这里简单的实现以下。

写了两种加载的方式

第一种是: Thread.currentThread().getContextClassLoader().getResourceAsStream(path);这个是直接获取到src/resource/

第二种是:InputStream input = new BufferedInputStream(new FileInputStream(new File(path)));绝对路径。

package com.cn.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class LoadProperties {

private static Logger log = LoggerFactory.getLogger(LoadProperties.class);
private static String path = "E:\\MainProgram\\program\\swtech-service-hbsxt\\src\\main\\resources\\redis.properties";

//privatet static String path = "redis.properties"
private static Properties pro = new Properties();

/*
public static void main(String[] args) {
log.info("-------------进入- - - - - - - - - - - - - - - -");
try {
pro.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(path));
String value = pro.getProperty("redis.hostName");
log.info("----------value------------:" + value);
} catch (IOException e) {
e.printStackTrace();
}
}
*/

static {
log.info("-----------进入- - - - - -- - - - - -");
String value = null;
//读取
try {
//第二种绝对路径E:\MainProgram\program\swtech-service-hbsxt\src\main\resources
InputStream input = new BufferedInputStream(new FileInputStream(new File(path)));
//第一种相对路径src/main/resources(直接填写resources下面的内容即可)
//InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
pro.load(input);
/*
* keySet键的集合。 entrySet键值对的集合
*/
Set <Object> keyset = pro.keySet();
//获得这个集合的迭代器
Iterator<Object> iter = keyset.iterator();
//用作遍历set中的每一个键
while(iter.hasNext()) {//hasNext()检查序列中是否还有元素。
String key = (String)iter.next();//next()获得序列中的下一个元素。
//属性编码
String propertiesEncoding = "utf-8";
value = new String(pro.getProperty(key).getBytes("ISO-8859-1"),propertiesEncoding);
value = pro.getProperty(key);
pro.setProperty(key, value);
}
} catch (IOException e) {
e.printStackTrace();
}
}

public static String getProperty(String key) {
if(StringUtils.isBlank(key)) {
return null;
}
String value = pro.getProperty(StringUtils.trim(key));
return value == null ? null :StringUtils.trim(value);
}

public static void main(String[] args) {
String value = LoadProperties.getProperty("redis.maxIdle");
System.out.println(value);
}

}

 

转载于:https://www.cnblogs.com/books148/p/11469486.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值