import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* 专门用于读取配置文件,提供访问配置文件的方法。
* <pre>
* 文件内容为键值对形式,格式:key=value
* </pre>
* @author zql
* @createTime 2020-11-30 22:49:02
* @version 1.1
* @modifyLog 1.1 优化代码
*
*/
public class ReadPropertiesUtil {
private InputStream ins = null;
private Properties pro = null;
public ReadPropertiesUtil() {
}
/**
* @param pkg 所在包名,从src下开始,例如:top.zqlweb.config
* @param fileName 文件名
*/
public ReadPropertiesUtil(String pkg, String fileName) {
// 配置文件所在路经
String name = pkg.replaceAll("\\.", "/") + "/" + fileName + ".properties";
this.ins = ReadPropertiesUtil.class.getClassLoader().getResourceAsStream(name);
BufferedReader bf = new BufferedReader(new InputStreamReader(ins));
this.pro = new Properties();
try {
this.pro.load(bf);
} catch (IOException e) {
System.out.println(name + "文件没有找到,请检查路径!");
e.printStackTrace();
}
}
/**
* 通过key查询相应的value
* @author zql
* @createTime 2020-11-30 22:50:01
*
* @param key
* @return
*/
public String getPropertys(String key) {
return this.pro.getProperty(key);
}
/**
* 返回键值对大小
* @author zql
* @createTime 2020-11-30 22:50:17
*
* @return
*/
public int size() {
return this.pro.size();
}
/**
* 返回所有键值对
* @author zql
* @createTime 2020-11-30 22:50:27
*
* @return
*/
public Map<String, String> getMap() {
Map<String, String> map = new HashMap<String, String>();
for (Map.Entry<Object, Object> m : this.pro.entrySet()) {
map.put(m.getKey().toString(), m.getValue().toString());
}
return map;
}
/**
* 判断配置文件是否存在
* @author zql
* @createTime 2020-11-30 22:50:37
*
* @param filePath,从src下开始,格式:top/zqlweb/config/server.properties
* @return
*/
public boolean isExistProperties(String filePath) {
String paths = System.getProperty("user.dir") + "\\src\\" + filePath.replaceAll("/", "\\\\");
File file = new File(paths);
return file.exists();
}
}
配置文件读取工具类
最新推荐文章于 2024-05-10 10:58:32 发布