简体   繁体   中英

Decode input stream from UTF-8 and write that in log file

I have xml file which will come with UTF-8 encoding as a input stream to my code and i need to write that file to the log file. Below is the code that i tried but that does not work, it prints all the encoded fields.

Sending encoded input stream as

FileOutputStream streamer = new FileOutputStream(filename);
OutputStreamWriter writer = new OutputStreamWriter(streamer, "UTF-8");

writer output stream is fed to the below code as this.encodedInputStream

Code

    InputStreamReader decodedInputStream = new InputStreamReader(this.encodedInputStream , StandardCharsets.UTF_8);
    BufferedReader reader = new BufferedReader(decodedInputStream);
    String readLine = null;
    StringBuilder builder = new StringBuilder();
    try {
      while ((readLine = reader.readLine())!=null){
readLine = URLDecoder.decode(readLine, "UTF-8");
        builder.append(readLine);
      }
    }catch(Exception e){
        log.error("Exception while logging WSCallMFE", e);
    }
    String result = builder.toString();
    log.info(result);

Above code prints the below values

%3Cprop%3E%3Cjavavendor%3ETest+Test%3C%2Fjavavendor%3E%0A%3Cdrive%3EC%3A%3C%2Fdrive

Expected result

<prop><java.vendor>Test Test</java.vendor>
<drive>C:</drive>

If i pass the xml notepad file directly as input stream to this.encodedInputStream , then it gives the expected output. Any idea how can i convert the whole encoded file and get rid of encoded characters?

This looks like to be encoded with some URL Encoder . Here you can use URLDecoder from java.net to get rid of these encoded content:

System.out.println(URLDecoder.decode("%3Cprop%3E%3Cjavavendor%3ETest+Test%3C%2Fjavavendor%3E%0A%3Cdrive%3EC%3A%3C%2Fdrive\r\n", StandardCharsets.UTF_8));

Output:

<prop><javavendor>Test Test</javavendor>
<drive>C:</drive

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM