Loading

【从NIO到Netty】4.NIOchannel简介

一个读较大文件的Channel例子,

package org.scaventz.nio.mine;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class NioFileChannel {
    public static void main(String[] args) throws IOException {
        File file = new File("d:/test.txt");
        FileChannel channel = new FileInputStream(file).getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(4096);
        int i = 0;
        while ((i = channel.read(buffer)) != -1) {
            System.out.println(new String(buffer.array()));
            buffer.clear();
        }
    }
}

这里面也用到了buffer,并且在循环读取中,对buffer做了clear操作。
之所以需要在每次循环中clear一次buffer,是因为每次循环读取,buffer的position将等于4096,无法再读入数据了,而clear将重置position为0。

 

完成了对NIO三大组件,Buffer,Channle,Selector的介绍,现在可以介绍一个完整的NIO EchoServer的例子

posted @ 2020-06-26 04:10  注销111  阅读(117)  评论(0编辑  收藏  举报