酆都城主

博客园 首页 联系 订阅 管理

1、概述

Properties 继承于Hashtable,key和value都是字符串

2、使用

 1 public class ReadProperties {
 2 
 3     public static void main(String[] args) {
 4         Properties properties = new Properties();
 5         try {
 6             //加载配置文件
 7             properties.load(ReadProperties.class.getClassLoader().getResourceAsStream("application.properties"));
 8             /*遍历配置文件中key和value
 9               for (Map.Entry<Object, Object> entry : properties.entrySet()) {
10                 System.out.println(entry.getKey() + ":" + entry.getValue());
11             }*/
12             //根据key获取value值
13             System.out.println(properties.getProperty("test.properties"));
14         } catch (IOException e) {
15             e.printStackTrace();
16         }
17     }
18 }

3、中文问题

默认情况下,properties文件是ISO-8859-1编码的,如果需要有中文的配置文件,我们可以使用eclipse等IDE把配置文件设置为UTF-8编码

 (1)选中配置文件-->右键-->Properties-->text file encoding

 (2)使用上述代码会出现乱码情况,修改为在load配置文件时指定编码格式为UTF-8

properties.load(new InputStreamReader(ReadProperties.class.getClassLoader().getResourceAsStream("application.properties"), "UTF-8"));

 

4、其它外部文件

根据load的参数可知,我们可以读取外部文件传入,这样就可以java工程配置文件单独放在包外面,不同的环境选用不同的配置

1 File file = new File("E:\\data\\application2.properties");
2 FileInputStream fileInputStream = new FileInputStream(file);
3properties.load(new InputStreamReader(fileInputStream, "UTF-8"));

 

posted on 2019-08-22 14:28  酆都城主  阅读(8424)  评论(0编辑  收藏  举报