【从BIO到Netty】4.NIOchannel简介
2021-01-30 21:13
标签:etc sys net getch pac nio position tty ioc 一个读较大文件的Channel例子, 这里面也用到了buffer,并且在循环读取中,对buffer做了clear操作。 【从BIO到Netty】4.NIOchannel简介 标签:etc sys net getch pac nio position tty ioc 原文地址:https://www.cnblogs.com/heben/p/13193721.htmlpackage 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();
}
}
}
之所以需要在每次循环中clear一次buffer,是因为每次循环读取,buffer的position将等于4096,无法再读入数据了,而clear将重置position为0。
下一篇:js统计字符
文章标题:【从BIO到Netty】4.NIOchannel简介
文章链接:http://soscw.com/index.php/essay/49196.html