Question

I'm working on a chat app for both Android and for PCs, which communicates with each other using sockets. The problem is that although I need the app to be workable with Japanese, the Android side makes character code problems.

The server works on a PC, and everything goes fine when all clients are on PCs, so I tried to do all the encoding/decoding on the Android side. On both clients, I tried System.getProperty("file.encoding");

and found out that the PC uses Shift_JIS and Android uses UTF-8. So I did

//on the Android output
OutputStream output = socket.getOutputStream();
PrintWriter writer = new PrintWriter(output);
writer.println(new String(msg.getBytes(), "Shift_JIS"));
writer.flush();

//on the Android input
InputStream input = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line = reader.readLine();
String lineDec = new String(line.getBytes("Shift_JIS"), "UTF-8");

but still got the character code problems.

I've tried changing "Shift_JIS" and "UTF-8" for each other but still didn't work... If you have any advices I'd be very happy. Thank you!

Was it helpful?

Solution

Why are you calling String.getBytes()? You can create an OutputStreamWriter / InputStreamReader and specify the charset with the constructor. This will take care of string to byte stream conversion using the appropriate charset. Simply explicitly specify UTF-8 on both sides. Something like:

OutputStream output = socket.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(output, "UTF-8");
writer.println("message");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top