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