最后填充空字节的字节数组:如何有效地复制到较小的字节数组

有:

[46][111][36][11][101][55][87][30][122][75][66][32][49][55][67][77][88][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0] 

想:

 [46][111][36][11][101][55][87][30][122][75][66][32][49][55][67][77][88] 

我有一个字节大小为8192的数组,从第一个数组中的某个索引开始,直到数组的结尾,字节都是空字节。 因此,数组末尾可能有6000个字节的值和2196个空字节。 如何有效地创建一个大小的新数组(6000)并复制这些字节? 注意:我不知道有多少空字节或带有值的字节。

这是我的尝试:

 static byte[] trim(byte[] bytes) { int i = bytes.length - 1; while (i >= 0 && bytes[i] == 0) { --i; } return Arrays.copyOf(bytes, i + 1); } public static void main(String[] args) { byte[] bytes = { 0, 1, 2, 0, 3, 4, 5, 0, 6, 0, 0, 7, 8, 9, 10, 0, 0, 0, 0 }; byte[] trimmed = trim(bytes); return; } 

为什么不在系统类中尝试静态方法数组副本只需给出源数组src的起始位置,目标数组,目标起始位置和长度

  System.arraycopy(src, srcPos, dest, destPos, length); byte [] dest= new byte [6000]; System.arraycopy(src, 0, dest, 0, 6000); 

我想我们也可以这样做

 byte []array={0, 69, 0, 71, 0, 72}; byte ar[]=new String(array).replaceAll("\0", "").getBytes();