为了账号安全,请及时绑定邮箱和手机立即绑定

非拉丁字符显示为“?”

非拉丁字符显示为“?”

莫回无 2022-07-20 12:20:26
我有一个像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。
查看完整描述

1 回答

?
慕容3067478

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);

}

另见CharsetDecoderCodingErrorAction



查看完整回答
反对 回复 2022-07-20
  • 1 回答
  • 0 关注
  • 74 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信