从ByteBuffer读取定长字节

对一个方法的优化引发的危机
原方法:
public static byte[] splitBytes(ByteBuffer buffer, int length) {
    byte[] source = new byte[length];
    buffer.get(source);
    return source;
 }

思考:这个方法会报什么错呢?

很显然,如果要获取的长度,buffer中没有,是不是就会报异常呢?!
于是,改进如下:

    public static byte[] splitBytes(ByteBuffer buffer, int length) {
        byte[] source = new byte[0];
        if (buffer.remaining() >= length) {
            source = new byte[length];
            buffer.get(source);
        } else {
            log.error("buffer的剩余长度与读取长度不符!");
        }
        return source;
    }

思考: 为什么一定要大于等于?!

详解:

1、大于:ByteBuffer 包含的字节长度,能满足只取出length长度的字节的要求。
2、等于:如果ByteBuffer只有length长度的字节,那么刚好可以取出来。所以,这也是最容易漏掉的条件。绝对不能少!

Returns the number of elements between the current position and the limit.
Returns:
The number of elements remaining in this buffer

public final int remaining() {
   return limit - position;
}

ByteBuffer详解,见下一期。

在Android中,使用串口通信时,数据可能会被拆包,因此需要使用ByteBuffer来拼接数据。以下是一个简单的示例代码: ```java public class SerialPortUtil { private SerialPort mSerialPort; private InputStream mInputStream; private OutputStream mOutputStream; public SerialPortUtil(String path, int baudrate) throws SecurityException, IOException, InvalidParameterException { mSerialPort = new SerialPort(new File(path), baudrate, 0); mInputStream = mSerialPort.getInputStream(); mOutputStream = mSerialPort.getOutputStream(); } public void sendData(byte[] data) throws IOException { mOutputStream.write(data); } public byte[] receiveData() throws IOException { byte[] buffer = new byte[1024]; ByteBuffer byteBuffer = ByteBuffer.allocate(1024); int size; while ((size = mInputStream.read(buffer)) != -1) { byteBuffer.put(buffer, 0, size); if (size < buffer.length) { break; } } byte[] result = new byte[byteBuffer.position()]; byteBuffer.rewind(); byteBuffer.get(result); return result; } } ``` 在上面的代码中,我们使用了ByteBuffer来拼接接收到的数据。首先创建一个大小为1024的byte数组作为缓冲区,然后创建一个ByteBuffer对象,使用allocate方法分配1024字节的空间。在循环中,每次读取一定数量的数据到缓冲区中,并使用put方法将数据添加到ByteBuffer对象中。如果读取的数据量小于缓冲区的大小,则表明数据已经接收完成,退出循环。最后,我们使用position方法获取实际接收到的数据长度,并使用rewind方法将ByteBuffer对象的位置重置为0,然后使用get方法获取实际接收到的数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值