欢迎访问我的个人网站==》 jiashubing.cn

读取Properties文件以及中文乱码问题

在java类中常见的读取Properties文件方式,是使用Properties.load(inputStream);的方式但是常常出现中文乱码问题,这就很尴尬了

public synchronized void load(InputStream inStream) throws IOException {
    load0(new LineReader(inStream));
}

 

看了很久才发现,还有一个重载的方法, 它的参数是Reader,如下:

public synchronized void load(Reader reader) throws IOException {
    load0(new LineReader(reader));
}

 

Reader是可以指定字符集的编码格式的,于是尝试如下更改:

 1 static{
 2     //初始化读取配置文件中的分表信息
 3     Resource resource = new ClassPathResource("splitTable.properties");
 4     Properties props = new Properties();
 5     try {
 6         InputStream is = resource.getInputStream();
 7         try {
 8             BufferedReader bf = new BufferedReader(new InputStreamReader(is, "UTF-8"));
 9             props.load(bf);
10         } finally {
11             is.close();
12         }
13     } catch (IOException e) {
14         e.printStackTrace();
15     }
16     projectMap = new HashMap<String,String>((Map) props);
17 }

 

顺利解决了问题。遇到无法解决的函数,查看其重载的方法用来替换,是个很重要的技巧啊,很可能柳暗花明又一村了

posted @ 2017-06-19 10:33  贾树丙  阅读(9124)  评论(0编辑  收藏  举报