package testnio;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;
public class TestNIO {
public static void main(String[] args) throws IOException {
RandomAccessFile aFile = new RandomAccessFile("C:/Users/Administrator/Desktop/新建文本文档.txt", "rw");
FileChannel inChannel = aFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(48);// 每次读多少和字节
int bytesRead = inChannel.read(buf);// 把数据读到buffer
while (bytesRead != -1) {
System.out.println("Read " + bytesRead);
buf.flip();// 将buffer 从写模式 切换到读模式
while (buf.hasRemaining()) {
System.out.print((char) buf.get());
}
buf.clear();// 读完后必须要清楚缓冲区,才可以继续向buffer写数据
bytesRead = inChannel.read(buf);
}
aFile.close();
}
}
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;
public class TestNIO {
public static void main(String[] args) throws IOException {
RandomAccessFile aFile = new RandomAccessFile("C:/Users/Administrator/Desktop/新建文本文档.txt", "rw");
FileChannel inChannel = aFile.getChannel();
ByteBuffer buf = ByteBuffer.allocate(48);// 每次读多少和字节
int bytesRead = inChannel.read(buf);// 把数据读到buffer
while (bytesRead != -1) {
System.out.println("Read " + bytesRead);
buf.flip();// 将buffer 从写模式 切换到读模式
while (buf.hasRemaining()) {
System.out.print((char) buf.get());
}
buf.clear();// 读完后必须要清楚缓冲区,才可以继续向buffer写数据
bytesRead = inChannel.read(buf);
}
aFile.close();
}
}