53

How to make the PrintWriter to write UTF-8?

pstream = new PrintWriter(csocket.getOutputStream(), true);
String res = "some string";
pstream.println(res); // here I want to output string as UTF-8
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
yeah its me
  • 1,131
  • 4
  • 18
  • 27

6 Answers6

63

Use an OutputStreamWriter:

pstream = new PrintWriter(new OutputStreamWriter(
    csocket.getOutputStream(), StandardCharsets.UTF_8), true)
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Njol
  • 3,271
  • 17
  • 32
7
OutputStream os = new FileOutputStream("file.txt");
PrintWriter pw = new PrintWriter(new OutputStreamWriter(os, "UTF-8"));
Krzysztof
  • 111
  • 1
  • 6
3

Look at Java: Difference between PrintStream and PrintWriter discussion.

To be quick: you can use -Dfile.encoding=utf8 JVM parameter or method suggested in the discussion (see second answer).

Community
  • 1
  • 1
Daniil
  • 5,760
  • 5
  • 18
  • 29
1
PrintWriter out1 = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    out1 = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8),true);
} else { 
    out1 = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"), true);
}
Tunaki
  • 132,869
  • 46
  • 340
  • 423
Shahab Saalami
  • 862
  • 10
  • 18
1

Don't user PrintWriter. If you need UTF-8 encoding, just write direct to the OutputStream.

csocket.getOutputStream().write(res.getBytes("UTF-8"));
Dakkaron
  • 5,930
  • 2
  • 36
  • 51
dave110022
  • 64
  • 5
  • While that is possible, that does not provide one with a `Writer` what OP is likely looking for. – Oliver Gondža Jan 23 '19 at 11:49
  • 1
    There are cases where `java.io.PrintWriter` cannot be avoided, such as when subclassing `javax.servlet.http.HttpServletResponseWrapper`. – Parker Sep 22 '20 at 16:09
  • I agree with writing direct to an OutputStream that way you actually know exactly what's going on. Using wrappers in a great class hierarchy usually takes for ever to get them to work - simplicity is better. – dave110022 Nov 07 '21 at 09:09
0

you can only write to file with any charset, otherwise platform default charset used see doc

Error
  • 820
  • 1
  • 11
  • 34