努力的方向 之一 NIO 续二
2017-05-09 00:00
190 查看
读取文件涉及三个步骤:(1) 从 FileInputStream 获取 Channel,(2) 创建 Buffer,(3) 将数据从 Channel 读到 Buffer 中。
在 NIO 中写入文件类似于从文件中读取。
缓冲区内部细节
NIO 中两个重要的缓冲区组件:状态变量和访问方法 (accessor)
状态变量
position
变量跟踪已经写了多少数据。更准确地说,它指定了下一个字节将放到数组的哪一个元素中。
limit
变量表明还有多少数据需要取出(在从缓冲区写入通道时),或者还有多少空间可以放入数据(在从通道读入缓冲区时)。 position 总是小于或者等于 limit。
capacity
缓冲区的 capacity 表明可以储存在缓冲区中的最大数据容量。limit 决不能大于 capacity。
flip() 方法
1.它将 limit 设置为当前 position。
2.它将 position 设置为 0。
clear() 方法
1.它将 limit 设置为与 capacity 相同。
2.它设置 position 为 0。
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。
相关文章推荐
- 努力的方向 之一 NIO 续二
- 努力的方向 之一 NIO
- 努力的方向 之一 NIO 续一
- 努力的方向 之一 NIO 续二
- 努力的方向 之一 NIO
- 努力的方向 之一 NIO
- 精神到处文章老,学问深时意气平(努力方向)——Leo2014年终总结
- 最可贵的努力,是选择一个正确的方向
- 正确的方向胜过无谓的努力
- 把握今天,向一个方向努力!
- 培训总结---方向比努力重要
- 生活是不易的,迷茫是暂时的,需要努力,需要方向
- 努力的方向 之一 NIO 续一
- 2015第1周六2015技术努力方向
- 为何找不到一个努力的方向
- 培训总结---方向比努力重要
- 未来的世界是,方向比努力重要,能力比知识重要,健康比成绩重要,生活比文凭重要,情商比智商重要!
- 转载的时下热门AR,对于努力方向有一定启示作用