java讀取配置文件以及中文亂碼問題


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"));

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM