Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make the PrintWriter to write UTF-8?

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
like image 364
yeah its me Avatar asked Jan 13 '14 16:01

yeah its me


People also ask

How do you write UTF in Java?

The readUTF() and writeUTF() methods in Java It provides 3 types of encodings. UTF-8 − It comes in 8-bit units (bytes), a character in UTF8 can be from 1 to 4 bytes long, making UTF8 variable width. UTF-16-8 − It comes in 16-bit units (shorts), it can be 1 or 2 shorts long, making UTF16 variable width.

How do you write a PrintWriter in Java?

Create a PrintWriter PrintWriter package first. Once we import the package here is how we can create the print writer. // Creates a FileWriter FileWriter file = new FileWriter("output. txt"); // Creates a PrintWriter PrintWriter output = new PrintWriter(file, autoFlush);

How do I change the encoding of a file in Java?

System. setProperty("file. encoding", "UTF-8"); byte inbytes[] = new byte[1024]; FileInputStream fis = new FileInputStream("response. txt"); fis.


3 Answers

Use an OutputStreamWriter:

pstream = new PrintWriter(new OutputStreamWriter(
    csocket.getOutputStream(), StandardCharsets.UTF_8), true)
like image 66
Njol Avatar answered Oct 01 '22 09:10

Njol


OutputStream os = new FileOutputStream("file.txt");
PrintWriter pw = new PrintWriter(new OutputStreamWriter(os, "UTF-8"));
like image 6
Krzysztof Avatar answered Oct 01 '22 09:10

Krzysztof


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).

like image 3
Daniil Avatar answered Oct 01 '22 07:10

Daniil