java nio的通道类似流,但又有些不同:
既可以从通道中读取数据,又可以写数据到通道。但流的读写通常是单向的。
通道可以异步地读写。
通道中的数据总是要先读到一个buffer,或者总是要从一个buffer中写入。
正如上面所说,从通道读取数据到缓冲区,从缓冲区写入数据到通道。如下图所示:
这些是java nio中最重要的通道的实现:
filechannel
datagramchannel
socketchannel
serversocketchannel
filechannel 从文件中读写数据。
datagramchannel 能通过udp读写网络中的数据。
socketchannel 能通过tcp读写网络中的数据。
serversocketchannel可以监听新进来的tcp连接,像web服务器那样。对每一个新进来的连接都会创建一个socketchannel。
下面是一个使用filechannel读取数据到buffer中的示例:
<code>01</code>
<code>randomaccessfile afile =</code><code>new</code> <code>randomaccessfile(</code><code>"data/nio-data.txt"</code><code>,</code><code>"rw"</code><code>);</code>
<code>02</code>
<code>filechannel inchannel = afile.getchannel();</code>
<code>03</code>
<code>04</code>
<code>bytebuffer buf = bytebuffer.allocate(</code><code>48</code><code>);</code>
<code>05</code>
<code>06</code>
<code>int</code> <code>bytesread = inchannel.read(buf);</code>
<code>07</code>
<code>while</code> <code>(bytesread != -</code><code>1</code><code>) {</code>
<code>08</code>
<code>09</code>
<code>system.out.println(</code><code>"read "</code> <code>+ bytesread);</code>
<code>10</code>
<code>buf.flip();</code>
<code>11</code>
<code>12</code>
<code>while</code><code>(buf.hasremaining()){</code>
<code>13</code>
<code>system.out.print((</code><code>char</code><code>) buf.get());</code>
<code>14</code>
<code>}</code>
<code>15</code>
<code>16</code>
<code>buf.clear();</code>
<code>17</code>
<code>bytesread = inchannel.read(buf);</code>
<code>18</code>
<code>19</code>
<code>afile.close();</code>
注意 buf.flip() 的调用,首先读取数据到buffer,然后反转buffer,接着再从buffer中读取数据。下一节会深入讲解buffer的更多细节。