天天看點

byte數組 合并 與 截取(java)

 合并數組

/**
* 合并byte[]數組 (不改變原數組)
* @param byte_1
* @param byte_2
* @return 合并後的數組
*/
public byte[] byteMerger(byte[] byte_1, byte[] byte_2){  
byte[] byte_3 = new byte[byte_1.length+byte_2.length];  
System.arraycopy(byte_1, 0, byte_3, 0, byte_1.length);  
System.arraycopy(byte_2, 0, byte_3, byte_1.length, byte_2.length);  
return byte_3;  
    }      

截取數組

/**
* 截取byte數組   不改變原數組
* @param b 原數組
* @param off 偏內插補點(索引)
* @param length 長度
* @return 截取後的數組
*/
public byte[] subByte(byte[] b,int off,int length){
byte[] b1 = new byte[length];
System.arraycopy(b, off, b1, 0, length);
return b1;
    }      

采用的JAVA_API:

System.arraycopy(src, srcPos, dest, destPos, length)

參數解析:

src:byte源數組
srcPos:截取源byte數組起始位置(0位置有效)
dest,:byte目的數組(截取後存放的數組)
destPos:截取後存放的數組起始位置(0位置有效)
length:截取的資料長度      

對于很多人上邊的方法已經足夠使用了,但是對于多個位元組數組合并與截取就稍微顯得相形見绌!java官方提供了一種操作位元組數組的方法——記憶體流(位元組數組流)ByteArrayInputStream、ByteArrayOutputStream,值得一提的是這個流内部采用的也是System.arraycopy該API,是以不是很複雜的功能的話,采用上方的方法就好

ByteArrayOutputStream——byte數組合并

/**
* 将所有的位元組數組全部寫入記憶體中,之後将其轉化為位元組數組
*/
public static void main(String[] args) throws IOException {
String str1 = "132";
String str2 = "asd";
ByteArrayOutputStream os = new ByteArrayOutputStream();
os.write(str1.getBytes());
os.write(str2.getBytes());
byte[] byteArray = os.toByteArray();
System.out.println(new String(byteArray));
    }      

ByteArrayInputStream——byte數組截取

/**
*   從記憶體中讀取位元組數組
*/
public static void main(String[] args) throws IOException {
String str1 = "132asd";
byte[] b = new byte[3];
ByteArrayInputStream in = new ByteArrayInputStream(str1.getBytes());
in.read(b);
System.out.println(new String(b));
in.read(b);
System.out.println(new String(b));
    }