1 回答
TA贡献1773条经验 获得超3个赞
替换字符可能表示文件未使用指定的CharSet.
根据您构建阅读器的方式,您将获得有关格式错误输入的不同默认行为。
当你使用
Properties properties = new Properties();
try(FileInputStream inputStream = new FileInputStream(path);
Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) {
properties.load(reader);
System.out.println("Name label: " + properties.getProperty("name.label"));
} catch(FileNotFoundException e) {
log.debug("Couldn't find properties file. ", e);
} catch(IOException e) {
log.debug("Couldn't read properties file. ", e);
}
你得到一个Reader配置CharsetDecoder为替换无效输入的。相反,当您使用
Properties properties = new Properties();
try(Reader reader = Files.newBufferedReader(Paths.get(path))) { // default to UTF-8
properties.load(reader);
System.out.println("Name label: " + properties.getProperty("name.label"));
} catch(FileNotFoundException e) {
log.debug("Couldn't find properties file. ", e);
} catch(IOException e) {
log.debug("Couldn't read properties file. ", e);
}
将CharsetDecoder被配置为在格式错误的输入上引发异常。
为了完整起见,如果两个默认值都不符合您的需求,您可以通过以下方式配置行为:
Properties properties = new Properties();
CharsetDecoder dec = StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPLACE)
.replaceWith("!");
try(FileInputStream inputStream = new FileInputStream(path);
Reader reader = new InputStreamReader(inputStream, dec)) {
properties.load(reader);
System.out.println("Name label: " + properties.getProperty("name.label"));
} catch(FileNotFoundException e) {
log.debug("Couldn't find properties file. ", e);
} catch(IOException e) {
log.debug("Couldn't read properties file. ", e);
}
另见CharsetDecoder
和CodingErrorAction
。
添加回答
举报