ByteBuffer和byte数组互相转换

1. byte 数组转byteBuffer

	/**
	 * byte 数组转byteBuffer
	 * @param byteArray
	 */
	public static ByteBuffer byte2Byffer(byte[] byteArray) {
		
		//初始化一个和byte长度一样的buffer
		ByteBuffer buffer=ByteBuffer.allocate(byteArray.length);
		// 数组放到buffer中
		buffer.put(byteArray);
		//重置 limit 和postion 值 否则 buffer 读取数据不对
		buffer.flip();
		return buffer;
	}

2. byteBuffer 转 byte数组

/**
	 * byteBuffer 转 byte数组
	 * @param buffer
	 * @return
	 */
	public static byte[] bytebuffer2ByteArray(ByteBuffer buffer) {
		//重置 limit 和postion 值 
		buffer.flip();
		//获取buffer中有效大小
		int len=buffer.limit() - buffer.position();
		
		byte [] bytes=new byte[len];
		
		for (int i = 0; i < bytes.length; i++) {
		 bytes[i]=buffer.get();
			
		}
		
		return bytes;
	}

3.测试以上两个方法

public static void main(String[] args) {
		
		byte [] a=new byte[] {1,2,4,5,6,7,8,9};
		
		System.out.println("-----------byte2Byffer转换前----------");
		for (int i = 0; i < a.length; i++) {
			System.out.print(a[i]+",");
			
		}
		ByteBuffer buffer=byte2Byffer(a);
		System.out.println();
		System.out.println("-----------byte2Byffer转换后----------");
		int len=buffer.limit()-buffer.position();	
		for (int i = 0; i < len; i++) {
			System.out.print(buffer.get()+",");
			
		}
		System.out.println("\n-----------bytebuffer2ByteArray转换后----------");
		
		byte [] dest=bytebuffer2ByteArray(buffer);
		for (int i = 0; i < dest.length; i++) {
			System.out.print(dest[i]+",");
			
		}
		
	}

4.测试结果

-----------byte2Byffer转换前----------
1,2,4,5,6,7,8,9,
-----------byte2Byffer转换后----------
1,2,4,5,6,7,8,9,
-----------bytebuffer2ByteArray转换后----------
1,2,4,5,6,7,8,9,

你可能感兴趣的:(【常用Api】)