When I am running this program (I got most of it here: “UTF-8” encoding is not working in java build):
import java.io.Console;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class tester {
public static void main(String[] args) throws IOException {
String s = "¿Hola öäüñ how geht's tú?";
write(s);
}
private static void write(String s) throws IOException {
String encoding = new OutputStreamWriter(System.out).getEncoding();
Console console = System.console();
if (console != null) {
// if there is a console attached to the jvm, use it.
System.out.println("Using encoding " + encoding + " (Console)");
try (PrintWriter writer = console.writer()) {
writer.write(s);
writer.flush();
}
} else {
// fall back to "normal" system out
System.out.println("Using encoding " + encoding + " (System out)");
System.out.print(s);
}
}
}
It displays:
Using encoding Cp1252 (System out)
�Hola ���� how geht's t�?
In the terminal, whereas I want it to dispaly:
Using encoding UTF-8(or sth. else that works properly...) (System out)
¿Hola öäüñ how geht's tú?
But it doesn't.
I have activated utf-8 in the Project settings, the General settings and under Run configurations > common. And it still is not working. Any clue what I could try next?
Other examples with slightly awkward outcomes:
Line 9:
String s = "öäüñ";
Terminal:
Using encoding Cp1252 (System out)
���
Their literary the 'ñ' isn't even a �...? As well here:
Line 9:
String s = "ñ";
Terminal:
Using encoding Cp1252 (System out)
But:
Line 9:
String s = "how ñ wow";
Terminal:
Using encoding Cp1252 (System out)
how � wow
And if that could give you a better understanding this part of code:
String str = "¿Hola öäüñ how geht's tú?";
//invokes the getBytes() method and stores an array of bytes into array[]
byte array[] = str.getBytes("UTF8");
System.out.println("Encoded String: ");
//enhanced for loop that iterates over the array
for (byte x: array)
{
//prints the sequence of bytes
System.out.print(x+" ");
}
Gives that output in the Terminal:
Encoded String:
-62 -65 72 111 108 97 32 -61 -74 -61 -92 -61 -68 -61 -79 32 104 111 119 32 103 101 104 116 39 115 32 116 -61 -70 63