配置文件是utf-8编码,但是使用下面这种方式读取出来的中文还是乱码的:
public static void main(String[] args) throws Exception{
Properties p = loadProperty();
String a = p.getProperty("pro.key");
System.out.println(a);
}
private static Properties loadProperty() throws IOException {
Properties p = new Properties();
InputStream in = null;
try{
in = Test.Class.getClassLoader().getResourceAsStream("sms.properties");
p.load(in);
return p;
}finally {
IOUtils.closeQuietly(in);
}
}
原因是这种流读取方式是基于字节的,读取出来的字符编码是ISO-8859-1,做一下编码转换即可得到正确的数据:
public static void main(String[] args) throws Exception{
Properties p = loadProperty();
String a = p.getProperty("pro.key");
System.out.println(changeCharset(a,"ISO-8859-1","UTF-8"));
}
private static String changeCharset(String a,String charset1,String charset2){
try {
return new String(a.getBytes(charset1),charset2);
} catch (UnsupportedEncodingException e) {
throw new Error(e);
}
}
但这种方式让代码显得更加繁琐,可以直接使用reader来读取:
private Properties loadProperty() throws IOException {
Properties p = new Properties();
InputStream in = null;
BufferedReader reader = null;
InputStreamReader sr = null;
try{
in = this.getClass().getClassLoader().getResourceAsStream("sms.properties");
sr = new InputStreamReader(in);
reader = new BufferedReader(sr);
p.load(reader);
return p;
}finally {
IOUtils.closeQuietly(reader);
IOUtils.closeQuietly(sr);
IOUtils.closeQuietly(in);
}
}