本文共 1024 字,大约阅读时间需要 3 分钟。
java nio channel 和 流有一些小小的区别:
channel一般从(借助)buffer进行读写。
如下图所示:以下是Java NIO中最重要的Channel实现:
Here is a basic example that uses a FileChannel to read some data into a Buffer:
一个简单的例子:用FileChannel去读数据从Buffer里RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw"); FileChannel inChannel = aFile.getChannel(); ByteBuffer buf = ByteBuffer.allocate(48); int bytesRead = inChannel.read(buf); while (bytesRead != -1) { System.out.println("Read " + bytesRead); buf.flip(); while(buf.hasRemaining()){ System.out.print((char) buf.get()); } buf.clear(); bytesRead = inChannel.read(buf); } aFile.close();
注意buf.flip()
的调用,首先读入一个缓冲区,然后将内容弹出,然后读出数据。
转载地址:http://jjdvl.baihongyu.com/