用 Java 讀取 Properties 資源文件時,常會撞上兩個看似不起眼卻很惱人的問題:
原因在於 Properties 的解析規則:反斜線是續行符,未轉義的換行則被視為「該條配置結束」。針對這兩點,解法也很乾淨:
\,下一行會被拼接進同一個 value。\n 轉義序列代替回車。package apistudy;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropertiesTest2 {
public static void main(String[] args) {
Properties properties = new Properties();
try {
InputStream inputStream =
PropertiesTest2.class.getClassLoader().getResourceAsStream("test.properties");
properties.load(inputStream);
inputStream.close(); // 關閉流
} catch (IOException e) {
e.printStackTrace();
}
String key1 = properties.getProperty("key1");
String key2 = properties.getProperty("key2");
System.out.println(key1);
System.out.println(key2);
}
}
輸出結果:
Where did you take the picture? It's so beautiful! Spring Hibernate Ibatis Velocity Java Struts
對應的 test.properties 內容:
key1=Where did you take the picture? \ It's so beautiful! key2=Spring\nHibernate\nIbatis\nVelocity\nJava\nStruts
第一行的反斜線後面不能有多餘空格,否則續行會失效並把空格帶入 value。另外,Properties 文件的默認編碼是 ISO-8859-1,寫中文時需要額外處理,這也是下一篇文章要談的主題。