代码:
package com.gusy.common.utils;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
public class ConfigUtil {
private static Properties pro;
static {
// path
// 不以’/'开头时默认是从此类所在的包下取资源,以’/'开头则是从ClassPath根下获取。其只是通过path构造一个绝对路径,最终还是由ClassLoader获取资源。
InputStream input = ConfigUtil.class.getResourceAsStream("/config.properties");
pro = new Properties();
try {
pro.load(input);
pro.load(new InputStreamReader(input, "UTF-8"));
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 根据key获取value
public static String getValue(String key) {
return pro.getProperty(key);
}
// 调用
public static void main(String[] args) {
String value = ConfigUtil.getValue("appID");
System.out.println(value);
}
}
附件:config.properties在项目中地址
拓展:
1、java Class类中getResourceAsStream的用法:参考链接:
点击打开链接
2、类Proerties中的方法(参考):
本文介绍了一个Java实用工具类ConfigUtil,用于加载配置文件并按需读取属性值。该工具类使用Properties对象来加载资源文件,并支持指定字符集加载。
227

被折叠的 条评论
为什么被折叠?



