版本:JDK7
package java.nio;
public abstract class ByteBuffer extends Buffer implements Comparable<ByteBuffer> {
1// These fields are declared here rather than in Heap-X-Buffer in order to 2// reduce the number of virtual method invocations needed to access these 3// values, which is especially costly when coding small buffers. 4// 5final byte[] hb; // Non-null only for heap buffers 6final int offset; 7boolean isReadOnly; // Valid only for heap buffers 8 9 10ByteBuffer(int mark, int pos, int lim, int cap, byte[] hb, int offset) { 11 super(mark, pos, lim, cap); 12 this.hb = hb; 13 this.offset = offset; 14} 15 16ByteBuffer(int mark, int pos, int lim, int cap) { // package-private 17 this(mark, pos, lim, cap, null, 0); 18} 19 20 21// 创建一个容量为capacity的ByteBuffer对象 22public static ByteBuffer allocateDirect(int capacity) { 23 return new DirectByteBuffer(capacity); 24} 25 26 27// 创建一个容量为capacity的ByteBuffer对象 28public static ByteBuffer allocate(int capacity) { 29 if (capacity < 0) throw new IllegalArgumentException(); 30 return new HeapByteBuffer(capacity, capacity); 31} 32 33 34public static ByteBuffer wrap(byte[] array, int offset, int length) { 35 try { 36 return new HeapByteBuffer(array, offset, length); 37 } catch (IllegalArgumentException x) { 38 throw new IndexOutOfBoundsException(); 39 } 40} 41 42public static ByteBuffer wrap(byte[] array) { 43 return wrap(array, 0, array.length); 44} 45 46public abstract ByteBuffer slice(); 47public abstract ByteBuffer duplicate(); 48public abstract ByteBuffer asReadOnlyBuffer(); 49 50/** 51 * Reads the byte at this buffer's position, and then increments the position. 52 */ 53// 读取单个字节,并将position自增1 54public abstract byte get(); 55 56/** 57 * Writes the given byte into this buffer at the current position, and then increments the position. 58 */ 59// 将给定的单个字节写入缓冲区的当前位置,并将position自增1 60public abstract ByteBuffer put(byte b); 61 62 63// 读取指定位置的字节,注意:不会改变position 64public abstract byte get(int index); 65 66// 将给定的单个字节写入缓冲区的index位置,注意:不会改变position 67public abstract ByteBuffer put(int index, byte b); 68 69 70// -- Bulk get operations -- 71/** 72 * This method transfers bytes from this buffer into the given destination array. 73 */ 74// (从Buffer中)读取多个字节(从索引offset开始,读取length长度的数据)到dst中,如果Buffer剩余的空间小于length,则抛异常 75public ByteBuffer get(byte[] dst, int offset, int length) { 76 checkBounds(offset, length, dst.length); 77 if (length > remaining()) 78 throw new BufferUnderflowException(); 79 int end = offset + length; 80 for (int i = offset; i < end; i++) 81 dst[i] = get(); 82 return this; 83} 84 85/** 86 * This method transfers bytes from this buffer into the given destination array. 87 */ 88// 批量读取dst.length个字节到dst中,如果Buffer剩余的空间小于dst的length,则抛异常 89public ByteBuffer get(byte[] dst) { 90 return get(dst, 0, dst.length); 91} 92 93// -- Bulk put operations -- 94/** 95 * 将src中的数据写入Buffer的当前位置 96 */ 97public ByteBuffer put(ByteBuffer src) { 98 if (src == this) 99 throw new IllegalArgumentException(); 100 int n = src.remaining(); 101 if (n > remaining()) 102 throw new BufferOverflowException(); 103 for (int i = 0; i < n; i++) 104 put(src.get()); 105 return this; 106} 107 108public ByteBuffer put(byte[] src, int offset, int length) { 109 checkBounds(offset, length, src.length); 110 if (length > remaining()) 111 throw new BufferOverflowException(); 112 int end = offset + length; 113 for (int i = offset; i < end; i++) 114 this.put(src[i]); 115 return this; 116} 117 118public final ByteBuffer put(byte[] src) { 119 return put(src, 0, src.length); 120} 121 122 123// -- Other stuff -- 124 125/** 126 * Tells whether or not this buffer is backed by an accessible byte array. 127 * 128 * <p> If this method returns <tt>true</tt> then the {[@link](https://my.oschina.net/u/393) #array() array} 129 * and {[@link](https://my.oschina.net/u/393) #arrayOffset() arrayOffset} methods may safely be invoked. 130 * </p> 131 * 132 * [@return](https://my.oschina.net/u/556800) <tt>true</tt> if, and only if, this buffer 133 * is backed by an array and is not read-only 134 */ 135public final boolean hasArray() { 136 return (hb != null) && !isReadOnly; 137} 138 139/** 140 * Returns the byte array that backs this 141 * buffer <i>(optional operation)</i>. 142 * 143 * <p> Modifications to this buffer's content will cause the returned 144 * array's content to be modified, and vice versa. 145 * 146 * <p> Invoke the {[@link](https://my.oschina.net/u/393) #hasArray hasArray} method before invoking this 147 * method in order to ensure that this buffer has an accessible backing 148 * array. </p> 149 * 150 * [@return](https://my.oschina.net/u/556800) The array that backs this buffer 151 * 152 * @throws ReadOnlyBufferException 153 * If this buffer is backed by an array but is read-only 154 * 155 * @throws UnsupportedOperationException 156 * If this buffer is not backed by an accessible array 157 */ 158public final byte[] array() { 159 if (hb == null) throw new UnsupportedOperationException(); 160 if (isReadOnly) throw new ReadOnlyBufferException(); 161 return hb; 162} 163 164/** 165 * Returns the offset within this buffer's backing array of the first 166 * element of the buffer <i>(optional operation)</i>. 167 * 168 * <p> If this buffer is backed by an array then buffer position <i>p</i> 169 * corresponds to array index <i>p</i> + <tt>arrayOffset()</tt>. 170 * 171 * <p> Invoke the {@link #hasArray hasArray} method before invoking this 172 * method in order to ensure that this buffer has an accessible backing 173 * array. </p> 174 * 175 * @return The offset within this buffer's array 176 * of the first element of the buffer 177 * 178 * @throws ReadOnlyBufferException 179 * If this buffer is backed by an array but is read-only 180 * 181 * @throws UnsupportedOperationException 182 * If this buffer is not backed by an accessible array 183 */ 184public final int arrayOffset() { 185 if (hb == null) throw new UnsupportedOperationException(); 186 if (isReadOnly) throw new ReadOnlyBufferException(); 187 return offset; 188} 189 190/** 191 * Compacts this buffer. 压缩并整理Buffer。 192 * 193 * The bytes between the buffer's current position and its limit, if any, are copied to the beginning of the buffer. 194 * That is, the byte at index p=position() is copied to index zero, 195 * the byte at index p+1 is copied to index one, 196 * and so forth until the byte at index limit()-1 is copied to index n=limit()-1-p 197 * The buffer's position is then set to n+1 and its limit is set to its capacity. The mark, if defined, is discarded. 198 * 199 * 即:将所有未读的数据拷贝到Buffer的起始处,然后将position设到最后一个未读元素的后面 200 * limit设置为capacity,此时,如果向Buffer中写数据,则不会覆盖之前未读的数据! 201 * 与clear()方法的比较: 202 * 如果Buffer中存在未读的数据,调用clear()方法后,这些未读的数据将会被“遗忘”,因为在clear之后,position的值为0,故无法确定未读数据的位置。 203 */ 204public abstract ByteBuffer compact(); 205 206/** 207 * Tells whether or not this byte buffer is direct. </p> 208 */ 209public abstract boolean isDirect(); 210 211 212public String toString() { 213 StringBuffer sb = new StringBuffer(); 214 sb.append(getClass().getName()); 215 sb.append("[pos="); 216 sb.append(position()); 217 sb.append(" lim="); 218 sb.append(limit()); 219 sb.append(" cap="); 220 sb.append(capacity()); 221 sb.append("]"); 222 return sb.toString(); 223} 224 225/** 226 * Returns the current hash code of this buffer. 227 */ 228public int hashCode() { 229 int h = 1; 230 int p = position(); 231 for (int i = limit() - 1; i >= p; i--) 232 h = 31 * h + (int)get(i); 233 return h; 234} 235 236/** 237 * Tells whether or not this buffer is equal to another object. 238 * 239 * They have the same element type, 240 * They have the same number of remaining elements, 241 * and The two sequences of remaining elements, 242 * considered independently of their starting positions, are pointwise equal. 243 * 244 * 即:Buffer中元素的类型相同,并且剩余的元素完全相同,则返回true 245 * 注意:并不是比较Buffer的所有数据,只是比较Buffer中的剩余数据。 246 */ 247public boolean equals(Object ob) { 248 if (this == ob) 249 return true; 250 if (!(ob instanceof ByteBuffer)) 251 return false; 252 ByteBuffer that = (ByteBuffer)ob; 253 if (this.remaining() != that.remaining()) 254 return false; 255 int p = this.position(); 256 for (int i = this.limit() - 1, j = that.limit() - 1; i >= p; i--, j--) 257 if (!equals(this.get(i), that.get(j))) 258 return false; 259 return true; 260} 261 262private static boolean equals(byte x, byte y) { 263 return x == y; 264} 265 266/** 267 * Compares this buffer to another. 268 * 269 * 比较两个Buffer的剩余元素 270 * 一个Buffer“小于”另一个Buffer的场景: 271 * 第一个不相等的元素小于另一个Buffer中对应的元素 272 * 所有元素都相等,但是第一个Buffer的元素个数小于另一个Buffer的个数 273 */ 274public int compareTo(ByteBuffer that) { 275 int n = this.position() + Math.min(this.remaining(), that.remaining()); 276 for (int i = this.position(), j = that.position(); i < n; i++, j++) { 277 int cmp = compare(this.get(i), that.get(j)); 278 if (cmp != 0) 279 return cmp; 280 } 281 return this.remaining() - that.remaining(); 282} 283 284private static int compare(byte x, byte y) { 285 return Byte.compare(x, y); 286} 287 288// -- Other char stuff -- 289 290// -- Other byte stuff: Access to binary data -- 291 292 293boolean bigEndian = true; // package-private 294 295boolean nativeByteOrder = (Bits.byteOrder() == ByteOrder.BIG_ENDIAN); // package-private 296 297 298/** 299 * Retrieves this buffer's byte order. 300 * 301 * <p> The byte order is used when reading or writing multibyte values, and 302 * when creating buffers that are views of this byte buffer. The order of 303 * a newly-created byte buffer is always {@link ByteOrder#BIG_ENDIAN 304 * BIG_ENDIAN}. </p> 305 * 306 * @return This buffer's byte order 307 */ 308public final ByteOrder order() { 309 return bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN; 310} 311 312/** 313 * Modifies this buffer's byte order. </p> 314 * 315 * @param bo 316 * The new byte order, 317 * either {@link ByteOrder#BIG_ENDIAN BIG_ENDIAN} 318 * or {@link ByteOrder#LITTLE_ENDIAN LITTLE_ENDIAN} 319 * 320 * @return This buffer 321 */ 322public final ByteBuffer order(ByteOrder bo) { 323 bigEndian = (bo == ByteOrder.BIG_ENDIAN); 324 nativeByteOrder = (bigEndian == (Bits.byteOrder() == ByteOrder.BIG_ENDIAN)); 325 return this; 326} 327 328// Unchecked accessors, for use by ByteBufferAs-X-Buffer classes 329// 330abstract byte _get(int i); // package-private 331abstract void _put(int i, byte b); // package-private 332 333 334/** 335 * Relative <i>get</i> method for reading an int value. 336 * 337 * <p> Reads the next four bytes at this buffer's current position, 338 * composing them into an int value according to the current byte order, 339 * and then increments the position by four. </p> 340 * 341 * @return The int value at the buffer's current position 342 * 343 * @throws BufferUnderflowException 344 * If there are fewer than four bytes 345 * remaining in this buffer 346 */ 347public abstract int getInt(); 348 349/** 350 * Relative <i>put</i> method for writing an int 351 * value <i>(optional operation)</i>. 352 * 353 * <p> Writes four bytes containing the given int value, in the 354 * current byte order, into this buffer at the current position, and then 355 * increments the position by four. </p> 356 * 357 * @param value 358 * The int value to be written 359 * 360 * @return This buffer 361 * 362 * @throws BufferOverflowException 363 * If there are fewer than four bytes 364 * remaining in this buffer 365 * 366 * @throws ReadOnlyBufferException 367 * If this buffer is read-only 368 */ 369public abstract ByteBuffer putInt(int value); 370 371/** 372 * Absolute <i>get</i> method for reading an int value. 373 * 374 * <p> Reads four bytes at the given index, composing them into a 375 * int value according to the current byte order. </p> 376 * 377 * @param index 378 * The index from which the bytes will be read 379 * 380 * @return The int value at the given index 381 * 382 * @throws IndexOutOfBoundsException 383 * If <tt>index</tt> is negative 384 * or not smaller than the buffer's limit, 385 * minus three 386 */ 387public abstract int getInt(int index); 388 389/** 390 * Absolute <i>put</i> method for writing an int 391 * value <i>(optional operation)</i>. 392 * 393 * <p> Writes four bytes containing the given int value, in the 394 * current byte order, into this buffer at the given index. </p> 395 * 396 * @param index 397 * The index at which the bytes will be written 398 * 399 * @param value 400 * The int value to be written 401 * 402 * @return This buffer 403 * 404 * @throws IndexOutOfBoundsException 405 * If <tt>index</tt> is negative 406 * or not smaller than the buffer's limit, 407 * minus three 408 * 409 * @throws ReadOnlyBufferException 410 * If this buffer is read-only 411 */ 412public abstract ByteBuffer putInt(int index, int value); 413 414/** 415 * Creates a view of this byte buffer as an int buffer. 416 * 417 * <p> The content of the new buffer will start at this buffer's current 418 * position. Changes to this buffer's content will be visible in the new 419 * buffer, and vice versa; the two buffers' position, limit, and mark 420 * values will be independent. 421 * 422 * <p> The new buffer's position will be zero, its capacity and its limit 423 * will be the number of bytes remaining in this buffer divided by 424 * four, and its mark will be undefined. The new buffer will be direct 425 * if, and only if, this buffer is direct, and it will be read-only if, and 426 * only if, this buffer is read-only. </p> 427 * 428 * @return A new int buffer 429 */ 430public abstract IntBuffer asIntBuffer(); 431 432// ...
}