Java NIO Buffer的三个重要属性
Buffer中3个重要状态属性的含义:position(位置),limit(限制)与capacity(容量)。
- example:
public static void main(String[] args) {
IntBuffer buffer = IntBuffer.allocate(10);
System.out.println("capacity:" + buffer.capacity());
for (int i = 0; i < 5; ++i) {
int randomNumber = new SecureRandom().nextInt(20);
buffer.put(randomNumber);
}
System.out.println("before flip limit:" + buffer.limit());
buffer.flip();
System.out.println("after flip limit:" + buffer.limit());
System.out.println("enter while loop");
while (buffer.hasRemaining()) {
System.out.println("position:" + buffer.position());
System.out.println("limit:" + buffer.limit());
System.out.println("capacity:" + buffer.capacity());
System.out.println("元素:" + buffer.get());
}
System.out.println("position:" + buffer.position());
System.out.println("limit:" + buffer.limit());
System.out.println("capacity:" + buffer.capacity());
}
buffer-flip方法以及3个属性.jpg
文件通道用法
通过NIO读取文件涉及到3个步骤:
1 从FileInputStrem获取FileChannel对象
2 创建Buffer
3 将数据从Channel读取到Buffer
绝对方法和相对方法的含义:
1 相对方法:limit值与position值会在操作时被考虑到。
2 绝对方法:完全忽略掉limit值与position值。
- example:
public static void main(String[] args) throws Exception {
FileInputStream inputStream = new FileInputStream("test.png");
FileOutputStream outputStream = new FileOutputStream("output.png");
FileChannel inputStreamChannel = inputStream.getChannel();
FileChannel outputStreamChannel = outputStream.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
while (true) {
byteBuffer.clear();
int read = inputStreamChannel.read(byteBuffer);
System.out.println(read);
if (-1 == read) {
break;
}
byteBuffer.flip();
outputStreamChannel.write(byteBuffer);
}
inputStream.close();
outputStream.close();
}
网友评论