PrintWriter won't write in UTF-8 - java

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

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

BufferedWriter isn't accepting second input from client?

I have a server and client application. They both use a BufferedWriter-InputStreamReader-InputStream to read information coming from the server, or coming from the client
I have it working so I can use
bw.write("command");
to execute a command on the server side, and output the information back to the client-side.
However, I am running into trouble doing it twice, for two different commands. Here's the code:
Server-sided code:
public void run() {
try {
while (true) {
socket.setTcpNoDelay(true);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String input = br.readLine();
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
if (input.equals("increment")) {
bw.write(String.valueOf(totalBets.incrementAndGet()));
bw.newLine();
bw.flush();
} else if(input.equals("generate")) {
Random rand = new Random();
bw.write(String.valueOf(rand.nextDouble()*99));
bw.newLine();
bw.flush();
}
}
}
Client-sided code:
public void actionPerformed(ActionEvent arg0) {
try {
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
bw.write("increment" + "\n");
bw.flush();
String id = br.readLine();
bw.write("generate");
bw.flush();
String roll = br.readLine();
}
}
The first String id gets the output from running the bw.write("increment"), but when I try to run bw.write("generate"), it freezes when running the line: String roll = br.readLine();
Any help?
Thank you!
I suggest that you use PrintWriter rather than BufferedWriter. Use BufferedReader to read without leaving data in the underlying operating system's buffers, so they will be buffered at application level, but for writing you want it to go out as soon as you send one complete 'command'.
With a PrintWriter you can also use println which should solve your problem.
You're losing data, or risking it, by creating multiple BufferedReaders. Use the same one for the life of the socket. Ditto the BufferedWriter.

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

Java UTF-8 encoding not working HttpURLConnection

I tried to do post call and to pass input with this value - "ä€愛لآहที่"
I got error message
{"error":{"code":"","message":{"lang":"en-US","value":{"type":"ODataInputError","message":"Bad Input: Invalid JSON format"}}}}
This is my code
conn.setRequestMethod(ConnectionMethod.POST.toString());
conn.setRequestProperty(CONTENT_LENGTH, Integer.toString(content.getBytes().length));
conn.setRequestProperty("Accept-Charset", "UTF-8");
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(content);
wr.flush();
wr.close();
InputStream resultContentIS;
String resultContent;
try {
resultContentIS = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(resultContentIS));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
it falied on conn.getInputStream();
The value of content is
{ "input" : "ä€愛لآहที่" }
It is working where the input is String or integer
When I added the statement
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
I got different message
{"error":{"code":"","message":{"lang":"en-US","value":{"type":"Error","message":"Internal server error"}}}}
Please try this code below:
DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(wr, "UTF-8"));
writer.write(content);
writer.close();
wr.close();
You should use JSONObject to pass params
The input, please try
BufferedReader reader = new BufferedReader(new InputStreamReader(resultContentIS, "UTF-8"));
If the out put is: ???????, so do not worry because your output console do not support UTF-8
It seems that your variable content does already have the wrong data because you may have converted a String without any attention to the required encoding.
Setting the correct enconding on the writer and use write() instead of writeBytes() should be worth a try.
You have to send content via byte array
DataOutputStream outputStream= new DataOutputStream(conn.getOutputStream());
outputStream.write(content.toString().getBytes());
This is completely solution for your file name character problems. The imported point is string sending via byte array. Every character changing via byte character. This is prevent your character encoding problems.

Skip creating file in FileOutputStream when there is no data in Inputstream

This is a logging function which logs error stream from the execution of an external program. Everything works fine. But I do not want to generate the log file when there is no data in error stream. Currently it is creating zero size file. Please help.
FileOutputStream fos = new FileOutputStream(logFile);
PrintWriter pw = new PrintWriter(fos);
Process proc = Runtime.getRuntime().exec(externalProgram);
InputStreamReader isr = new InputStreamReader(proc.getErrorStream());
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null)
{
if (pw != null){
pw.println(line);
pw.flush();
}
}
Thank you.
Simply defer the creating of the FileOutputStream and PrintWriter until you need it:
PrintWriter pw = null;
Process proc = Runtime.getRuntime().exec(externalProgram);
InputStreamReader isr = new InputStreamReader(proc.getErrorStream());
BufferedReader br = new BufferedReader(isr);
String line;
while ( (line = br.readLine()) != null)
{
if (pw == null)
{
pw = new PrintWriter(new FileOutputStream(logFile));
}
pw.println(line);
pw.flush();
}
Personally I'm not a big fan of PrintWriter - the fact that it just swallows all exceptions concerns me. I'd also use OutputStreamWriter so that you can explicitly specify the encoding. Anyway, that's aside from the real question here.
The obvious thing to do is to change
FileOutputStream fos = new FileOutputStream(logFile);
PrintWriter pw = new PrintWriter(fos);
....
if (pw != null){
...
}
to
FileOutputStream rawLog = null;
try {
PrintWriter Log = null;
....
if (log == null) {
rawLog = new FileOutputStream(logFile);
log = new PrintWriter(log, "UTF-8");
}
...
} finally {
// Thou shalt close thy resources.
// Icky null check - might want to split this using the Execute Around idiom.
if (rawLog != null) {
rawLog.close();
}
}

Categories