对一个方法的优化引发的危机
原方法:
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详解,见下一期。