首页 > 其他 > 详细

NIO文件读取

时间:2020-04-06 21:54:43      阅读:69      评论:0      收藏:0      [点我收藏+]
已转移
public
static void main( String[] args ) throws Exception { RandomAccessFile aFile = new RandomAccessFile("file1.txt", "rw"); FileChannel inChannel = aFile.getChannel(); ByteBuffer buf = ByteBuffer.allocate(48);//分配空间 //读取指定字节到buf中,将pos设为bytesRead(读取的字节数),limit设为分配空间48 int bytesRead = inChannel.read(buf); while (bytesRead != -1) { buf.flip();//转换为读模式,将limit设为pos,pos设为0,准备从buf取数据 while(buf.hasRemaining()){//判断buf中pos是否小于limit, System.out.print((char) buf.get());//获取一个字节,pos+1 } buf.clear();//清空buf,将limit设为分配空间48,pos设为0 bytesRead = inChannel.read(buf);//再次读取 } aFile.close(); }

FileChannel 是操作文件的Channel, 我们可以通过 FileChannel 从一个文件中读取数据, 也可以将数据写入到文件中.
注意, FileChannel 不能设置为非阻塞模式.

即转换为读模式

NIO文件读取

原文:https://www.cnblogs.com/xyfaneast/p/10737158.html

(1)
(1)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!