ObjectOutputStream方法:writeBytes(String str)vs writeUTF(String s); [英] ObjectOutputStream methods: writeBytes(String str) vs writeUTF(String s);

查看:100
本文介绍了ObjectOutputStream方法:writeBytes(String str)vs writeUTF(String s);的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两者之间的主要区别是什么?

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?

推荐答案

在文档中...来自

It's in the documentation... from DataOutput.writeBytes(String):

将字符串写入输出流.对于字符串s中的每个字符,按顺序取一个字节写入输出流.如果s为null,则抛出NullPointerException.

Writes a string to the output stream. For every character in the string s, taken in order, one byte is written to the output stream. If s is null, a NullPointerException is thrown.

如果s.length为零,则不写入任何字节.否则,先写字符s [0],然后写s

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);的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆