非拉丁字符显示为“?”

我有一个像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。


莫回无
浏览 75回答 1
1回答

慕容3067478

替换字符可能表示文件未使用指定的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。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java