public class ByteUtil {
/**
* 系統提供的陣列拷貝方法arraycopy
* */
public static byte[] sysCopy(List<byte[]> srcArrays) {
int len = 0;
for (byte[] srcArray:srcArrays) {
len+= srcArray.length;
}
byte[] destArray = new byte[len];
int destLen = 0;
for (byte[] srcArray:srcArrays) {
System.arraycopy(srcArray, 0, destArray, destLen, srcArray.length);
destLen += srcArray.length;
}
return destArray;
}
/**
* 借助位元組輸出流ByteArrayOutputStream來實現位元組陣列的合併
* */
public static byte[] streamCopy(List<byte[]> srcArrays) {
byte[] destAray = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
for (byte[] srcArray:srcArrays) {
bos.write(srcArray);
}
bos.flush();
destAray = bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bos.close();
} catch (IOException e) {
}
}
return destAray;
}
 
public static void main(String[] args) {
List<byte[]> bytes = new ArrayList<byte[]>();
byte[] byte1 = new byte[3];
byte1[0] = 1;
byte1[1] = 2;
byte1[2] = 3;
bytes.add(byte1);
byte[] byte2 = new byte[3];
byte2[0] = 4;
byte2[1] = 5;
byte2[2] = 6;
bytes.add(byte2);
byte[] byte3 = new byte[3];
byte3[0] = 7;
byte3[1] = 8;
byte3[2] = 9;
bytes.add(byte3);
byte[] newByte = sysCopy(bytes);
System.out.println("方法一:");
for (int i = 0; i < newByte.length; i++) {
System.out.print(newByte[i]+" ");
}
System.out.println();
System.out.println("方法二:");
newByte = streamCopy(bytes);
for (int i = 0; i < newByte.length; i++) {
System.out.print(newByte[i]+" ");
}
}
}
arrow
arrow
    全站熱搜

    戮克 發表在 痞客邦 留言(0) 人氣()