读取配置文件。在这里简单的实现以下。
写了两种加载的方式
第一种是: 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);
}
}