标签:etc sys net getch pac nio position tty ioc
一个读较大文件的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。
标签:etc sys net getch pac nio position tty ioc
原文地址:https://www.cnblogs.com/heben/p/13193721.html