将 Java 字节数组的一部分追加到 StringBuilder

发布于 2024-10-16 10:19:49 字数 371 浏览 6 评论 0原文

如何在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

痴意少年 2024-10-23 10:19:49

您不应为此使用 StringBuilder,因为这可能会导致可变宽度编码出现编码错误。您可以使用 java.io.ByteArrayOutputStream 来代替,并在读取所有数据后将其转换为字符串:

byte[] buffer = new byte[4096];
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream is;
//
//some setup code
//
while (is.available() > 0) {
   int len = is.read(buffer);
   out.write(buffer, 0, len);
}
String result = out.toString("UTF-8"); // for instance

如果已知编码不包含多字节序列(您正在使用 ASCII 数据) ,例如),那么使用 StringBuilder 就可以了。

You should not use a StringBuilder for this, since this can cause encoding errors for variable-width encodings. You can use a java.io.ByteArrayOutputStream instead, and convert it to a string when all data has been read:

byte[] buffer = new byte[4096];
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream is;
//
//some setup code
//
while (is.available() > 0) {
   int len = is.read(buffer);
   out.write(buffer, 0, len);
}
String result = out.toString("UTF-8"); // for instance

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.

给妤﹃绝世温柔 2024-10-23 10:19:49

您可以从缓冲区中创建一个字符串:

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.

故人爱我别走 2024-10-23 10:19:49

像下面这样的东西应该可以帮助你。

byte[] buffer = new byte[3];
buffer[0] = 'a';
buffer[1] = 'b';
buffer[2] = 'c';
StringBuilder sb = new StringBuilder(new String(buffer,0,buffer.length-1));
System.out.println("buffer has:"+sb.toString()); //prints ab

Something like below should do the trick for you.

byte[] buffer = new byte[3];
buffer[0] = 'a';
buffer[1] = 'b';
buffer[2] = 'c';
StringBuilder sb = new StringBuilder(new String(buffer,0,buffer.length-1));
System.out.println("buffer has:"+sb.toString()); //prints ab
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文