Search code examples
javadataoutputstream

Java write(str.getBytes()) vs writeBytes(str)


When using DataOutputStream to push Strings, I normally do the following:

DataOutputStream dout;
String str;
dout.write(str.getBytes());

I just came across the writeBytes() method of DataOutputStream, and my question is whether the above is equivalent to:

dout.writeBytes(str);

If not, what is difference and when should it be used?


Solution

  • No, it is not equivalent.

    The Javadocs for writeBytes say

    Writes out the string to the underlying output stream as a sequence of bytes. Each character in the string is written out, in sequence, by discarding its high eight bits.

    So this will not work well except for ASCII Strings.

    You should be doing

    dout.write(str.getBytes(characterSet));
    // remember to specify the character set, otherwise it become 
    // platform-dependent and the result non-portable
    

    or

    dout.writeChars(str);
    

    or

    dout.writeUTF(str);
    

    Note that only the last method also writes the length of the String, so for the others, you probably need to know exactly what you are doing if you intend to later read it back.


    The bigger question is why you need to use such a low-level protocol as DataOutputStream directly.