其他分享
首页 > 其他分享> > NIO

NIO

作者:互联网

使用FileChannel读取数据到buffer中的示例

public class FileChannelDemo1 {
    public static void main(String[] args) throws Exception {
        //FileChannel读取数据到buffer
        //创建FileChannel
        RandomAccessFile aFile = new RandomAccessFile("e:\\01txt", "rw");
        FileChannel channel = aFile.getChannel();

        //创建buffer
        ByteBuffer buf = ByteBuffer.allocate(1024);

        //读取数据到buffer中
        int bytesRead = channel.read(buf);
        while (bytesRead != -1){
            System.out.println("读取了: " + bytesRead);
            buf.flip();
            while (buf.hasRemaining()){
                System.out.println((char) buf.get());
            }
            buf.clear();
            bytesRead = channel.read(buf);
        }
        aFile.close();
        System.out.println("测试结束");
    }
}

 

标签:NIO,buffer,buf,System,FileChannel,bytesRead,读取数据
来源: https://www.cnblogs.com/zuiqiangJAVA/p/15942833.html