package com.test.nio;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class TestFile {
/**
* @param args
* @throws FileNotFoundException
*/
public static void main(String[] args) throws Exception {
RandomAccessFile aFile=new RandomAccessFile("H:/test.txt","rw");
FileChannel inChannel=aFile.getChannel();
/*分配buffer */
ByteBuffer buf=ByteBuffer.allocate(2);
/*读入到buffer*/
int bytesRead=inChannel.read(buf);
while(bytesRead!=-1)
{
/*设置读*/
buf.flip();
/*开始读取*/
while(buf.hasRemaining())
{
System.out.print((char)buf.get());
}
buf.clear();
bytesRead=inChannel.read(buf);
}
aFile.close();
}
}
FileChannel我们可以理解为一个file的流,然后我们利用ByteBuffer绑定到这个文件流中,最后把文件流全部读取出来。
输出结果
ByteBuffer buf=ByteBuffer.allocate(2);这句话是分配一个buffer,大小为两个字节。
int bytesRead=inChannel.read(buf);这句话是从文件流中读取一个buf内容,返回读取的大小,如果是读取到文件尾部的时候,返回的是-1。
/*设置读*/
buf.flip();
/*开始读取*/
while(buf.hasRemaining())
{
System.out.print((char)buf.get());
}
buf.clear();
这段话是设置buf为读模式,然后循环输出buf里面的内容,最后清空整个buf。
bytesRead=inChannel.read(buf);这句话继续读取文件流buf大小的内容。