Java NIO的通道类似流,但又有些不同:
正如上面所说,从通道读取数据到缓冲区,从缓冲区写入数据到通道。如下图所示:
这些是Java NIO中最重要的通道的实现:
FileChannel 从文件中读写数据。
DatagramChannel 能通过UDP读写网络中的数据。
SocketChannel 能通过TCP读写网络中的数据。
ServerSocketChannel可以监听新进来的TCP连接,像Web服务器那样。对每一个新进来的连接都会创建一个SocketChannel。
下面是一个使用FileChannel读取数据到Buffer中的示例:
package java_.nio_.demo; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class FileChannelMain { public static void main(String[] args) throws Exception { RandomAccessFile raf = new RandomAccessFile("E:/edu/FileChannelMain.txt", "rw"); FileChannel fc = raf.getChannel(); ByteBuffer buf = ByteBuffer.allocate(1024); int bytesRead = fc.read(buf); while (bytesRead != -1) { System.out.println("Read : " + bytesRead); buf.flip(); while (buf.hasRemaining()) { System.out.print((char) buf.get()); } buf.clear(); bytesRead = fc.read(buf); } raf.close(); } }
注意 buf.flip() 的调用,首先读取数据到Buffer,然后反转Buffer,接着再从Buffer中读取数据。下一节会深入讲解Buffer的更多细节。
原文:http://www.cnblogs.com/ClassNotFoundException/p/6340085.html