PrintStream doesn't print correctly unicode characters ( UTF 16)

I want to print correctly unicode (let's say greek characters ) but I have problems. For example :

PrintStream oStream = new PrintStream(client.getOutputStream(), true, "UTF-8");
oStream.write(" Customer    : Γειά σου\r\n".getBytes());
oStream.write(" ΚΩΔΙΚΟΣ     : 00000234242\r\n".getBytes());
oStream.flush();
oStream.close();

                             OR
 OutputStreamWriter oStream = new OutputStreamWriter(client.getOutputStream(), "UTF-16");
    oStream.write(" Customer    : Γειά σου\r\n");
oStream.write(" ΚΩΔΙΚΟΣ     : 00000234242\r\n");
oStream.flush();
oStream.close();

The question is if there is any solution to print correctly all of the caharacters. I think for Greek characters UTF-16 is ok.

Jon Skeet
people
quotationmark

This is quite possibly the issue:

oStream.write(" Customer    : Γειά σου\r\n".getBytes());
oStream.write(" ΚΩΔΙΚΟΣ     : 00000234242\r\n".getBytes());

You're calling String.getBytes() with no encoding, to get a byte array using the platform default encoding. That's almost always a bad idea anyway, and it means that the fact that you specified UTF-8 earlier is irrelevant to these two lines. By the time the PrintStream gets the data, it's already in binary.

Try this instead:

oStream.print(" Customer    : Γειά σου\r\n");
oStream.print(" ΚΩΔΙΚΟΣ     : 00000234242\r\n");

Notes:

  • I would advise against using either PrintStream or PrintWriter. They swallow exceptions.
  • If you're only writing text, you should use a Writer subclass rather than an OutputStream subclass
  • It's unclear whether your source code is even being handled correctly: you need to check that whatever you're using to compile your code knows what encoding your source file is using.

I suggest you wrap your output stream in an OutputStreamWriter... that will allow you to specify the encoding, you won't have to worry about accidentally writing binary data (as the API doesn't allow it) and you won't see exceptions getting swallowed.

people

See more on this question at Stackoverflow