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

Reading from property file containing utf 8 character

我正在读取一个 属性 文件,其中包含一条 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***********************}

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

使用 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.

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

将其设置为 UTF-8

您应该在构造 FileInputStream 对象时指定 UTF-8 编码。您可以使用此构造函数:

new FileInputStream("uinsoaptest.properties", "UTF-8");

如果您想更改 JVM 以便能够默认读取 UTF-8 文件,则必须将 JVM 选项中的 JAVA_TOOL_OPTIONS 更改为如下内容:

-Dfile.encoding=UTF-8

如果有人使用@Value 注解,可以试试StringUils。

@Value("${title}")
private String pageTitle;

public String getPageTitle() {
    return StringUtils.toEncodedString(pageTitle.getBytes(Charset.forName("ISO-8859-1")), Charset.forName("UTF-8"));
}