我有一个类似 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);
}
但它打印
Name label: ?
我使用的是java 8。
最佳答案
替换字符可能表明该文件未使用指定的 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
.
关于java - 非拉丁字符显示为 '?',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54978040/