NIO文件读取

已转移
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 不能设置为非阻塞模式.

即转换为读模式

猜你喜欢

转载自www.cnblogs.com/xyfaneast/p/10737158.html