java - 非拉丁字符显示为 '?'

标签 java java-8 properties

我有一个类似 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);
}

另请参阅CharsetDecoderCodingErrorAction .

关于java - 非拉丁字符显示为 '?',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54978040/

相关文章:

javascript - 我尝试存储在数据库中的任何内容都输入值 '0'

java - 将流列表转换为列表

objective-c - 在 ObjC 中设置只读属性

actionscript-3 - 为什么这个属性/函数名称冲突会在 AS3 中编译?

objective-c - 变量范围 Objective C

java - 无法启动 glassfish 服务器,因为无法获取/opt/glassfishv3/glassfish/domains/domain1/logs/server.log 的锁定

java - 为什么我的透明图标没有渲染为透明?

java - ArrayList 代码中的问题,有什么建议吗?

java - JAVA 中用于嵌套条件的 Lambda 表达式

java - 在 java 中,我如何处理 CompletableFutures 并获得第一个完成的理想结果?