Reputation: 57
I'm reading messages from a TCP connection. The sender is sending a byte array but the BufferedReader
reads it as a string. How can I convert the message to a byte array so I can then convert it to the actual message?
Say I want to send "hello". I use
String message = "hello"
byte[] byteData = message.getBytes();
I then send the message.
It's received as a string of, say, 0Bf3f3
.
I need to convert it back to "hello".
Upvotes: 0
Views: 90
Reputation: 2854
This is how to convert a byte array back to a String:
String message = "hello";
byte[] byteData = message.getBytes();
String retMessage = new String(byteData); // <===
Upvotes: 0
Reputation: 4309
java.lang.String
provides a constructor which takes an array of bytes. However, you need to keep in mind that the charset can be different at the receiver and sender side. For more details, see the javadoc.
Upvotes: 2