非拉丁字符显示为“?”

时间:2019-03-04 06:57:30

标签: 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);
}

但可以打印

  

名称标签:?

我正在使用Java 8。

1 个答案:

答案 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);
}

另请参阅CharsetDecoderCodingErrorAction