我有一个类似name.label=名
我的Java代码就像
Properties properties = new Properties();
try (FileInputStream inputStream = new FileInputStream(path)) {
Reader reader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
properties.load(reader);
System.out.println("Name label: " + properties.getProperty("name.label"));
reader.close();
} catch (FileNotFoundException e) {
log.debug("Couldn't find properties file. ", e);
} catch (IOException e) {
log.debug("Couldn't close input stream. ", e);
}
但可以打印
名称标签:?
我正在使用Java 8。
答案 0 :(得分:2)
替换字符可能表示该文件未使用指定的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);
}