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

时间:2023-03-09 18:39:23
读取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是可以指定字符集的编码格式的,于是尝试如下更改:

 static{
//初始化读取配置文件中的分表信息
Resource resource = new ClassPathResource("splitTable.properties");
Properties props = new Properties();
try {
InputStream is = resource.getInputStream();
try {
BufferedReader bf = new BufferedReader(new InputStreamReader(is, "UTF-8"));
props.load(bf);
} finally {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
projectMap = new HashMap<String,String>((Map) props);
}

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