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
。
添加回答
舉報