问题描述
两者之间的主要区别是什么?
What's the main difference between the two?
仍然它们都是用于编写String的.
Still both of them are for writing Strings.
public void writeUTF(String str)
throws IOException
Primitive data write of this String in modified UTF-8 format.
vs
public void writeBytes(String str)
throws IOException
Writes a String as a sequence of bytes.
何时应该使用一种而不是另一种?
When should I use one rather than the other?
推荐答案
在文档中...来自 DataOutput.writeBytes(String)
:
It's in the documentation... from DataOutput.writeBytes(String)
:
如果s.length为零,则不写入任何字节.否则,先写字符s [0],然后写s 1 ,依此类推;最后写入的字符是s [s.length-1].对于每个字符,完全按照writeByte方法的方式写入一个字节,即低位字节.字符串中每个字符的高八位都将被忽略.
If s.length is zero, then no bytes are written. Otherwise, the character s[0] is written first, then s1, and so on; the last character written is s[s.length-1]. For each character, one byte is written, the low-order byte, in exactly the manner of the writeByte method . The high-order eight bits of each character in the string are ignored.
换句话说,"Sod Unicode,我们不在乎ISO-8859-1中没有的任何字符.哦,我们假设您也不关心字符串的长度."
In other words, "Sod Unicode, we don't care about any characters not in ISO-8859-1. Oh, and we assume you don't care about the length of the string either."
请注意,writeBytes
甚至不会尝试检测数据损坏-如果您写出ISO-8859-1中不存在的字符,它只会静默丢弃高字节
Note that writeBytes
doesn't even try to detect data corruption - if you write out a character which isn't in ISO-8859-1, it will just drop the high byte silently.
请拒绝-writeUTF
是您的朋友...假设您的字符串长度小于64K.
Just say no - writeUTF
is your friend... assuming your string is less than 64K in length.
当然,如果您要尝试实现的协议本身需要单字节编码(ISO-8859-1或ASCII)并且不使用长度,则writeBytes
可能是适当的-但我个人可能自己执行文本到字节的转换,然后使用write(byte[])
代替...
Of course, if you have a protocol you're trying to implement which itself requires a single-byte encoding (ISO-8859-1 or ASCII) and doesn't use a length, then writeBytes
might be appropriate - but I'd personally probably perform the text-to-bytes conversion myself and then use write(byte[])
instead... it's clearer.
这篇关于ObjectOutputStream方法:writeBytes(String str)vs writeUTF(String s);的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!