Karthik Krishnan Karthik Krishnan -4 years ago 120
Java Question

How can I change the Standard Out to "UTF-8" in Java

I download a file from a website using a Java program and the header looks like below

Content-Disposition attachment;filename="Textkürzung.asc";


There is no encoding specified

What I do is after downloading I pass the name of the file to another application for further processing. I use

System.out.println(filename);


In the standard out the string is printed as
Textk³rzung.asc


How can I change the Standard Out to "UTF-8" in Java?

I tried to encode to "UTF-8" and the content is still the same

Update:

I was able to fix this without any code change. In the place where I call this my jar file from the other application, i did the following

java -DFile.Encoding=UTF-8 -jar ....


This seem to have fixed the issue

thank you all for your support

Answer Source

The result you're seeing suggests your console expects text to be in Windows "code page 850" encoding - the character ü has Unicode code point U+00FC. The byte value 0xFC renders in Windows code page 850 as ³. So if you want the name to appear correctly on the console then you need to print it using the encoding "Cp850":

PrintWriter consoleOut = new PrintWriter(new OutputStreamWriter(System.out, "Cp850"));
consoleOut.println(filename);

Whether this is what your "other application" expects is a different question - the other app will only see the correct name if it is reading its standard input as Cp850 too.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download