1、在src目录下创建application.properties文件;
2、创建读取资源文件的类
public class PropertiesUtil {
private static PropertiesUtil instance;
/* 默认文件名称 */
private final static String fileName = "application.properties";
private static Properties properties;
/**
* 初始化
*/
public static void init() {
if (null == instance) {
instance = new PropertiesUtil();
}
if (null == properties) {
properties = new Properties();
// 读取资源文件
InputStream inputStream = PropertiesUtil.class.getClassLoader()
.getResourceAsStream(fileName);
try {
properties.load(inputStream);
} catch (IOException ie) {
ie.printStackTrace();
}
}
}
public static PropertiesUtil getInstance() {
init();
return instance;
}
/**
* 读取资源文件
*
* @param key关键字
* @return
* @throws Exception
*/
public String getProperties(String key) {
try {
if (null == properties) {
init();
}
return properties.getProperty(key);
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
}
本文介绍了一种在Java中读取application.properties配置文件的方法。通过一个名为PropertiesUtil的工具类实现对属性文件的初始化及读取操作。该工具采用单例模式确保实例唯一,并通过静态方法提供获取实例及读取配置文件内容的功能。
3529

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



