从包含 utf 8 字符的属性文件中读取

新手上路,请多包涵

我正在读取一个包含 UTF-8 字符集中消息的属性文件。

问题

输出格式不正确。我正在使用 InputStream

属性文件看起来像

username=LBSUSER
password=Lbs@123
url=http://localhost:1010/soapfe/services/MessagingWS
timeout=20000
message=Spanish character are = {á é í, ó,ú ,ü, ñ, ç, å, Á, É, Í, Ó, Ú, Ü, Ñ, Ç, ¿, °, 4° año = cuarto año, €, ¢, £, ¥}

我正在这样阅读文件,

 Properties props = new Properties();
props.load(new FileInputStream("uinsoaptest.properties"));
String username = props.getProperty("username", "test");
String password = props.getProperty("password", "12345");
String url = props.getProperty("url", "12345");
int timeout = Integer.parseInt(props.getProperty("timeout", "8000"));
String messagetext = props.getProperty("message");
System.out.println("This is soap msg : " + messagetext);

上述消息的输出是

在此处输入图像描述

您可以在该行之后的控制台中看到消息

{************************ SOAP MESSAGE TEST***********************}

如果我能得到任何正确阅读此文件的帮助,我将不胜感激。我可以用另一种方法读取这个文件,但我正在寻找更少的代码修改。

原文由 Som 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 375
2 个回答

使用 InputStreamReaderProperties.load(Reader reader)

 FileInputStream input = new FileInputStream(new File("uinsoaptest.properties"));
props.load(new InputStreamReader(input, Charset.forName("UTF-8")));


作为一种方法,这可能类似于以下内容:

   private Properties read( final Path file ) throws IOException {
    final var properties = new Properties();

    try( final var in = new InputStreamReader(
      new FileInputStream( file.toFile() ), StandardCharsets.UTF_8 ) ) {
      properties.load( in );
    }

    return properties;
  }

不要忘记关闭您的流。 Java 7 引入了 StandardCharsets.UTF_8

原文由 Würgspaß 发布,翻译遵循 CC BY-SA 4.0 许可协议

使用 props.load(new FileReader("uinsoaptest.properties")) 代替。默认情况下,它使用编码 Charset.forName(System.getProperty("file.encoding")) 可以使用 System.setProperty("file.encoding", "UTF-8") 或命令行参数 -Dfile.encoding=UTF-8 设置为 UTF-8

原文由 Binkan Salaryman 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题