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
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.
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);
System. setProperty("file. encoding", "UTF-8"); byte inbytes[] = new byte[1024]; FileInputStream fis = new FileInputStream("response. txt"); fis.
Use an OutputStreamWriter
:
pstream = new PrintWriter(new OutputStreamWriter(
csocket.getOutputStream(), StandardCharsets.UTF_8), true)
OutputStream os = new FileOutputStream("file.txt");
PrintWriter pw = new PrintWriter(new OutputStreamWriter(os, "UTF-8"));
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With