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

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

当使用 DataOutputStream 推送字符串时,我通常会执行以下操作:

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

我刚刚遇到DataOutputStreamwriteBytes()方法,我的问题是上面是否等同于:

dout.writeBytes(str);

如果不是,有什么区别,应该在什么时候使用?

不,这不等价。

writeBytes 的 Javadocs 说

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.

因此,除了 ASCII 字符串外,这将无法正常工作。

你应该做的

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

dout.writeChars(str);

dout.writeUTF(str);

请注意,只有最后一个方法还写入字符串的长度,因此对于其他方法,如果您打算稍后再读回它,您可能需要确切地知道自己在做什么。


更大的问题是为什么您需要直接使用像 DataOutputStream 这样的 low-level 协议。