Java NIO的通道类似流,但又有些不同:
- 既可以从通道中读取数据,又可以写数据到通道。但流的读写通常是单向的。
- 通道可以异步地读写。
- 通道中的数据总是要先读到一个Buffer,或者总是要从一个Buffer中写入。
正如上面所说,从通道读取数据到缓冲区,从缓冲区写入数据到通道。如下图所示:
下面是一个用nio的channel读文件的例子
public static void nioReadFile() throws IOException { System.out.println("nio begin"); RandomAccessFile raf = new RandomAccessFile("D:\\test1.txt","rw"); RandomAccessFile rafc = new RandomAccessFile("D:\\test1.txt","rw"); //读取通道 FileChannel fc = raf.getChannel(); System.out.println("beg1: " + fc.size()); FileChannel fc2 = rafc.getChannel(); System.out.println("beg2: " + fc2.size()); ByteBuffer buffer = ByteBuffer.allocate(150); ByteBuffer buffer1 = ByteBuffer.allocate(150); //j将channel读入buffer int by = fc.read(buffer); System.out.println("beg: " + fc.size()); int byd = fc2.read(buffer1); System.out.println("beg213: " + byd); while (by != -1){//-1时说明没有内容(一个chaneel只能读一次?) //回归position 因为之前读过一次 buffer.flip(); System.out.println("posi2: " + buffer.position()); String a = ""; while (buffer.hasRemaining()){ // System.out.println("ppdfdf1: " + buffer.position()); char ab= (char)buffer.get(); a = a + ab; //System.out.println(ab); //System.out.println("ppsdfsdf2: " + buffer.position()); } System.out.println("sb:s1 " + buffer.position()); buffer.clear(); by = fc.read(buffer); } raf.close(); } public static void test() throws Exception { //声明randowFile RandomAccessFile a = new RandomAccessFile("D:\\test1.txt", "rw"); //获取channel FileChannel fc = a.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(500); //用buffer读入channerl fc.read(buffer); //buffeer回归初始position buffer.flip(); while (buffer.hasRemaining()){ System.out.print((char)buffer.get()); } fc.close(); }