简体   繁体   English

将部分java字节数组附加到StringBuilder

[英]append part of java byte array to StringBuilder

How do I append a portion of byte array to a StringBuilder object under Java? 如何将一部分字节数组附加到Java下的StringBuilder对象? I have a segment of a function that reads from an InputStream into a byte array. 我有一个函数段,从InputStream读取到一个字节数组。 I then want to append whatever I read into a StringBuilder object: 然后我想将我读到的任何内容追加到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
 }

You should not use a StringBuilder for this, since this can cause encoding errors for variable-width encodings. 您不应该使用StringBuilder ,因为这会导致可变宽度编码的编码错误。 You can use a java.io.ByteArrayOutputStream instead, and convert it to a string when all data has been read: 您可以使用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

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. 如果已知编码不包含多字节序列(例如,您正在使用ASCII数据),则使用StringBuilder将起作用。

You could just create a String out of your buffer: 你可以从缓冲区中创建一个String:

String s = new String(buffer, 0, len);

Then if you need to you can just append it to a StringBuilder. 然后,如果需要,可以将它附加到StringBuilder。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM