java 将字节流转换为字符串(UTF-8 编码)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6599135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert a stream of bytes to a String (UTF-8 encoded)
提问by Guillaume Brunerie
I have a stream of bytes (given by a BufferedInputStream) which represents a sequence of UTF-8 strings. The protocol is a little crappy becauses it uses 0xFF between commands, which implies that the whole stream is not a valid UTF-8 string, only the parts between the 0xFF are.
我有一个字节流(由 BufferedInputStream 给出),它表示一个 UTF-8 字符串序列。该协议有点糟糕,因为它在命令之间使用 0xFF,这意味着整个流不是有效的 UTF-8 字符串,只有 0xFF 之间的部分是。
How can I extract those UTF-8 strings.
我如何提取那些 UTF-8 字符串。
I don't think BufferedReader would work, because the 0xFF will mess up everything and I have found no byte array to UTF-8 string conversion function.
我不认为 BufferedReader 会起作用,因为 0xFF 会搞砸一切,而且我没有发现字节数组到 UTF-8 字符串转换函数。
采纳答案by Leonard Brünings
So would be new String(bytes, "UTF-8");
所以会 new String(bytes, "UTF-8");
You would need to filter the Stream beforehand though.
不过,您需要事先过滤 Stream。