Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading from property file containing utf 8 character

I am reading a property file which consists of a message in the UTF-8 character set.

Problem

The output is not in the appropriate format. I am using an InputStream.

The property file looks like

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

And I am reading the file like this,

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);

The output of the above message is

enter image description here

You can see the message in the console after the line

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

I will be obliged if I can get any help reading this file properly. I can read this file with another approach but I am looking for less code modification.

like image 939
Som Avatar asked Sep 01 '25 17:09

Som


1 Answers

Use an InputStreamReader with Properties.load(Reader reader):

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

As a method, this may resemble the following:

  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;
  }

Don't forget to close your streams. Java 7 introduced StandardCharsets.UTF_8.

like image 106
Würgspaß Avatar answered Sep 04 '25 08:09

Würgspaß