原文链接:java读取properties配置文件的几种方式
项目中经常将一些配置信息放到properties文件中,读取非常方便,下面介绍几种java读取properties配置文件的方式。先看示例的properties文件:

1.基于InputStream读取配置文件
根据实际情况处理转码问题
// 通过InputStream读取配置文件
private static void readPropertiesByInputStream() {
Properties properties = new Properties();
InputStream inputStream = Object.class.getResourceAsStream("/code.properties");
// Properties是用UTF-8编码的,所以需要用UTF-8解码
// 很多人没有设置文本的编码,通常是GBK的,相应改成GBK即可
InputStreamReader inputStreamReader = null;
try {
inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
properties.load(inputStreamReader);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(properties.get("warshipType.1"));
}
2. java.util.ResourceBundle类读取
private static void readPropertyByResourceBundle(){
ResourceBundle resourceBundle = ResourceBundle.getBundle("code");
// 遍历取值
Enumeration enumeration = resourceBundle.getKeys();
while(enumeration.hasMoreElements()){
try {
String value = resourceBundle.getString((String) enumeration.nextElement());
System.out.println(new String(value.getBytes("iso-8859-1"),"UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
3. Spring中的PropertiesLoaderUtils工具类进行获取
private static void readPropertyBySpringUtils() {
Properties properties = new Properties();
try {
properties = PropertiesLoaderUtils.loadAllProperties("code.properties");
System.out.println(new String(properties.getProperty("warshipType.2").getBytes("iso-8859-1"), "gbk"));
} catch (IOException e) {
e.printStackTrace();
}
}
本文介绍了三种在Java中读取properties配置文件的方法:使用InputStream、ResourceBundle类和Spring的PropertiesLoaderUtils工具类。每种方法都有其适用场景,文章详细展示了如何实现。

140

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



