How to make the PrintWriter to write UTF-8? - java

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

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

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);
}

Don't user PrintWriter. If you need UTF-8 encoding, just write direct to the OutputStream.
csocket.getOutputStream().write(res.getBytes("UTF-8"));

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

Related

Is there any way to convert PrintWriter into ByteArrayOutputStream?

I want to convert PrintWriter object into ByteArrayOutputStream. and this I am displaying as a PDF.
I don't know how you are using PrintWriter exactly (please post your code), but instead of converting objects you can write lines directly to ByteArrayOutputStream like this:
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(byteStream);
pw.write("example");
pw.flush();
or (flush after closing PrintWriter):
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(byteStream);
pw.write("example");
pw.close();
or (auto-flushable):
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(byteStream, true);
pw.println("example");
Let me know whether you prefer other solution and add some more details then(your code).

Can one write to a wrapped Stream in java?

I'm writing a java server for an assignment, and I have observed some strange behaviour when I write both into a wrapped stream and a wrapper stream, can this cause any problems ? As far as I see, it can, but how ? Pls enlighten me.
as an example:
OutputStream os = new OutputStream(...);
PrintWriter pw = new PrintWriter(os);
And I want to write both in the PrintWriter, and the OutputStream.
To transfer from byte-based stream to character-based stream, you need to use OutputStreamWriter:
An OutputStreamWriter is a bridge from character streams to byte streams.
So that would be:
OutputStream os = ...
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
PrintWriter pw = new PrintWriter(osw);
I think the problem is that you need to specify the encoding, since the constructor PrintWriter(OutputStream out) uses the default encoding which might not be correct for your data input:
OutputStream os = ...
PrintWriter pw = new PrintWriter(os, "UTF-8");

PrintWriter won't write in UTF-8

My code is
PrintWriter output = new PrintWriter(new OutputStreamWriter(new FileOutputStream(outputFile),
StandardCharsets.UTF_8), true);
output.print(SomeString);
but if i run this I Still have Problems wit ßÄÖÜ and so on.
is there someone how can explain me this?
If i do
System.out.print(someString);
it prints out perfect with äöüß
thanks for helping
res.setContentType("text/html; charset=UTF-8");
PrintWriter out = new PrintWriter(
new OutputStreamWriter(res.getOutputStream(), "UTF8"), true);
also you can check encoding type
String encoding = request.getCharacterEncoding();
if ((encoding != null) && (encoding.equalsIgnoreCase("utf-8")))
{
response.setContentType("text/html; charset=utf-8");
}

is there a way to set encoding when writing with RandomAccessFile

I open a text file using windows-1251 encoding
FileInputStream is = new FileInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(is,
"windows-1251"));
and later write the changes like:
RandomAccessFile file = new RandomAccessFile(new File(path), "rw");
try {
file.write(etMainView.getText().toString().getBytes());
file.close();
Toast.makeText(this, "Changes saved", Toast.LENGTH_SHORT)
.show();
//..... Exception handling
The problem is that it messes up all the non-latin letters in the file and when I open it again, all such letters are replaced with some unreadable characters. I guess the RandomAccessFile uses UTF-8 by default which is causing troubles. How can I save the file keeping the encoding I used to open it?
Use .getBytes("windows-1251") instead of .getBytes(); .getBytes() uses the default JVM encoding.
If you want to use the stream apis you can do it this way
RandomAccessFile file = ....;
FileChannel fc = file.getChannel();
OutputStream os = Channels.newOutputStream(fc);
OutputStreamWriter osw = new OutputStreamWriter(os, "windows-1251");
osw.write("Some sring");
osw.flush();
file.close();

Java text file I/O

Which is the fast way to write text file in java?
At the moment i use this way to write a text file:
FileOutputStream fos = new FileOutputStream('FileName');
DataOutputStream dos = new DataOutputStream(fos);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(dos, Charset.forName(this.config.getCharset())));
My file size will be up 3 GB.
Flush the buffer after significant chunk of data is written. FileOutputStream should be just enough for text files. There is no need for using DataOutputStream.
how about
FileOutputStream fos = new FileOutputStream('FileName');
BufferedOutputStream bof = new BufferedOutputStream(fos);
bof.write("some text".getBytes()); // or just byte array
or
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write("Some text");
You do not need to use DataOutputStream here.

Categories