gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 09:49:57 25 4
gpt4 key购买 nike

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

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

我刚刚发现了 writeBytes()方法DataOutputStream ,我的问题是上面是否相当于:

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这样的低级协议(protocol)。

关于Java write(str.getBytes()) 与 writeBytes(str),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56390704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com