|
| 1 | +package org.javacore.nio; |
| 2 | + |
| 3 | +import java.nio.ByteBuffer; |
| 4 | +import java.nio.IntBuffer; |
| 5 | + |
| 6 | +/* |
| 7 | + * Copyright [2015] [Jeff Lee] |
| 8 | + * |
| 9 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 10 | + * you may not use this file except in compliance with the License. |
| 11 | + * You may obtain a copy of the License at |
| 12 | + * |
| 13 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 14 | + * |
| 15 | + * Unless required by applicable law or agreed to in writing, software |
| 16 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 17 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 18 | + * See the License for the specific language governing permissions and |
| 19 | + * limitations under the License. |
| 20 | + */ |
| 21 | + |
| 22 | +/** |
| 23 | + * @author Jeff Lee |
| 24 | + * @since 2015-10-12 18:53:01 |
| 25 | + * 通过IntBuffer操作ByteBuffer的int型数据 |
| 26 | + */ |
| 27 | +public class IntBufferDemo { |
| 28 | + private static final int BSIZE = 1024;// 1字节 |
| 29 | + public static void main(String[] args) { |
| 30 | + // 创建1字节大小的字节缓冲区 |
| 31 | + ByteBuffer bb = ByteBuffer.allocate(BSIZE); |
| 32 | + // int视图缓冲区 |
| 33 | + IntBuffer ib = bb.asIntBuffer(); |
| 34 | + // 存储一个数组 |
| 35 | + ib.put(new int[]{1, 2, 3, 4, 5, 6}); |
| 36 | + // 通过访问ByteBuff字节缓冲区,获取某个位置的值 |
| 37 | + System.out.println(ib.get(3)); |
| 38 | + // 存储一个int数据 |
| 39 | + ib.put(3, 44); |
| 40 | + // 反转缓冲区 |
| 41 | + ib.flip(); |
| 42 | + // 如果当前位置还有元素 |
| 43 | + while (ib.hasRemaining()) { |
| 44 | + // 获取当前位置的元素 |
| 45 | + int i = ib.get(); |
| 46 | + System.out.println(i); |
| 47 | + } |
| 48 | + } |
| 49 | +} |
0 commit comments