First of all, you make a lot of assumptions about the chachachter encoding that you get from your client. Is it US-ASCII, ISO-8859-1, UTF-8?
Since there is no byte sequence in a Java string, when it comes to creating portable String serialization code, you have to make explicit decisions about character encoding. For this reason, you should NEVER use StringBuilder to convert bytes to String. If you look at the StringBuilder interface, you will notice that it does not even have an append( byte ) method, and this is not because the designers simply did not notice it.
In your case, you should definitely use ByteArrayOutputStream. The only drawback to using the direct implementation of ByteArrayOutputStream is that its toByteArray() method returns a copy of the array stored by the internaly object. For this reason, you can create your own subclass of ByteArrayOutputStream and provide direct access to the protected buf member.
Note that if you are not using the default implementation, be sure to specify the boundaries of the byte array in your String constructor. Your code should look something like this:
MyByteArrayOutputStream message = new MyByteArrayOutputStream( 1024 ); ... message.write( //byte from socket ); ... String messageStr = new String(message.buf, 0, message.size(), "ISO-8859-1");
Substitute ISO-8859-1 for a character set suitable for your needs.
source share