将 Java 字节数组的一部分追加到 StringBuilder
如何在 Java 下将字节数组的一部分附加到 StringBuilder
对象?我有一个函数的片段,它从 InputStream 读取到字节数组中。然后我想将我读到的任何内容附加到 StringBuilder 对象中:
byte[] buffer = new byte[4096];
InputStream is;
//
//some setup code
//
while (is.available() > 0)
{
int len = is.read(buffer);
//I want to append buffer[0] to buffer[len] into StringBuilder at this point
}
How do I append a portion of byte array to a StringBuilder
object under Java? I have a segment of a function that reads from an InputStream into a byte array. I then want to append whatever I read into a StringBuilder object:
byte[] buffer = new byte[4096];
InputStream is;
//
//some setup code
//
while (is.available() > 0)
{
int len = is.read(buffer);
//I want to append buffer[0] to buffer[len] into StringBuilder at this point
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不应为此使用
StringBuilder
,因为这可能会导致可变宽度编码出现编码错误。您可以使用 java.io.ByteArrayOutputStream 来代替,并在读取所有数据后将其转换为字符串:如果已知编码不包含多字节序列(您正在使用 ASCII 数据) ,例如),那么使用
StringBuilder
就可以了。You should not use a
StringBuilder
for this, since this can cause encoding errors for variable-width encodings. You can use ajava.io.ByteArrayOutputStream
instead, and convert it to a string when all data has been read:If the encoding is known not to contain multi-byte sequences (you are working with ASCII data, for instance), then using a
StringBuilder
will work.您可以从缓冲区中创建一个字符串:
String s = new String(buffer, 0, len);
然后,如果需要,您可以将其附加到 StringBuilder。
You could just create a String out of your buffer:
String s = new String(buffer, 0, len);
Then if you need to you can just append it to a StringBuilder.
像下面这样的东西应该可以帮助你。
Something like below should do the trick for you.