本文共 1513 字,大约阅读时间需要 5 分钟。
Java NIO的通道类似流,但又有些不同:
正如上面所说,从通道读取数据到缓冲区,从缓冲区写入数据到通道。
这些是Java NIO中最重要的通道的实现:
FileChannel 从文件中读写数据。
DatagramChannel 能通过UDP读写网络中的数据。
SocketChannel 能通过TCP读写网络中的数据。
ServerSocketChannel可以监听新进来的TCP连接,像Web服务器那样。对每一个新进来的连接都会创建一个SocketChannel。
基本channel示例
public void buffer01() { String director = "F:\\nio笔记.txt"; try { RandomAccessFile aFile = new RandomAccessFile(director,"rw"); FileChannel inChannel = aFile.getChannel(); //create buffer with capacity of 1024 bytes ByteBuffer buf = ByteBuffer.allocate(1024); //read into buffer. int bytesRead = inChannel.read(buf); while (bytesRead != -1) { System.out.println("Read " + bytesRead); //make buffer ready for read buf.flip(); while (buf.hasRemaining()) { // read 1 byte at a time System.out.println((char) buf.get()); } //make buffer ready for writing buf.clear(); bytesRead = inChannel.read(buf); } aFile.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
注意 buf.flip() 的调用,首先读取数据到Buffer,然后反转Buffer,接着再从Buffer中读取数据。
备注:文章参考
转载地址:http://njyab.baihongyu.com/