在多语言环境中需要保存配置数据,一般采用Unicode格式。在java中,默认是ASCII码格式文件。所以在读取Unicode格式文件的时候,要制定字符集。
譬如有一个Unicode格式的文件,命名为data.conf。里面保存一些名/值对(key/value pari),和properties文件内容是一样的,但是文件后缀名是.conf。现在想读取该文件。
String filePath = getFilePath("data.conf");
InputStreamReader isr = null;
try {
//Unicode file.
isr = new InputStreamReader(new FileInputStream(filePath ), "UTF-16");
// isr = new InputStreamReader(new FileInputStream(filePath ), "UNICODE");
final Properties props = new Properties();
props.load(isr);
//handle properties here
} catch (final FileNotFoundException e) {
throw new RuntimeException(e);
} catch (final IOException e) {
throw new RuntimeException(e);
} finally {
try {
isr.close();
} catch (final IOException ioe) {
throw new RuntimeException(ioe);
}
}
这样就可以正确地读出Unicode编码的文件内容了。