[英]How to concatenate multiple byte arrays into single string in Java?
例如,这里有一些字节 arrays:
byte[] firstArray = "first part ".getBytes();
byte[] secondArray = "second part ".getBytes();
byte[] thirdArray = "third part ".getBytes();
现在,我想将它们连接成单个字符串,就像这样:
(String) "first part second part third part ";
这里一种可能的解决方案是将 arrays 连接到一个新数组并将新数组转换为字符串。但是,我认为它会导致不必要的复制。 我想知道是否有更好的方法。
如果您只想使用 arrays,您可以计算出总大小并将部分复制到该数组中。
byte[] firstArray = "first part ".getBytes();
byte[] secondArray = "second part ".getBytes();
byte[] thirdArray = "third part ".getBytes();
byte[] finalArray = new byte[firstArray.length + secondArray.length + thirdArray.length];
System.arraycopy(firstArray, 0, finalArray, 0, firstArray.length);
System.arraycopy(secondArray, 0, finalArray, firstArray.length, secondArray.length);
System.arraycopy(thirdArray, 0, finalArray, firstArray.length + secondArray.length, thirdArray.length);
return new String(finalArray);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.