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

标签 java parsing encoding 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);

上述消息的输出是

enter image description here

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

{************************ SOAP 消息测试**************** ******}

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

最佳答案

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

关于java - 从包含 utf 8 字符的属性文件中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61177131/

相关文章:

java - 如何知道哪个线程受 notify() 或 notifyAll() 影响 - Java

java - Hazelcast -executeOnEntries 在第一次执行后停止

ruby-on-rails - 在 Rails 中解析 JSON

iPhone - GDataXMLNode 和 GDataXMLElement 之间的区别以及如何使用它们

mysql - 呸!我在 ruby​​ 1.9.2 的 Rails 中不断收到此编码错误

java - Android AsyncTask 中的多个请求

java - JFileChooser 关闭启动新窗口

parsing - 是否存在左关联前缀运算符或右关联后缀运算符之类的东西?

java - 将unicode写入rtf文件

python - 当cursor.fetchall()时出现UnicodeDecodeError