首页 > Web开发 > 详细

【从BIO到Netty】4.NIOchannel简介

时间:2020-06-26 10:38:42      阅读:74      评论:0      收藏:0      [点我收藏+]

一个读较大文件的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。

 

【从BIO到Netty】4.NIOchannel简介

原文:https://www.cnblogs.com/heben/p/13193721.html

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