您的位置:首页 > 其它

努力的方向 之一 NIO 续二

2017-05-09 00:00 162 查看
读取文件涉及三个步骤:(1) 从 FileInputStream 获取 Channel,(2) 创建 Buffer,(3) 将数据从 Channel 读到 Buffer 中。

FileInputStream fin = new FileInputStream( "readandshow.txt" );
FileChannel fc = fin.getChannel();
ByteBuffer buffer = ByteBuffer.allocate( 1024 );
fc.read( buffer );


在 NIO 中写入文件类似于从文件中读取。

FileOutputStream fout = new FileOutputStream( "writesomebytes.txt" );
FileChannel fc = fout.getChannel();
ByteBuffer buffer = ByteBuffer.allocate( 1024 );
for (int i=0; i<message.length; ++i) {
buffer.put( message[i] );
}
buffer.flip();
fc.write( buffer );


缓冲区内部细节

NIO 中两个重要的缓冲区组件:状态变量和访问方法 (accessor)

状态变量

position

变量跟踪已经写了多少数据。更准确地说,它指定了下一个字节将放到数组的哪一个元素中。

limit

变量表明还有多少数据需要取出(在从缓冲区写入通道时),或者还有多少空间可以放入数据(在从通道读入缓冲区时)。 position 总是小于或者等于 limit。

capacity

缓冲区的 capacity 表明可以储存在缓冲区中的最大数据容量。limit 决不能大于 capacity。

flip() 方法

1.它将 limit 设置为当前 position。

2.它将 position 设置为 0。

clear() 方法

1.它将 limit 设置为与 capacity 相同。

2.它设置 position 为 0。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: