Original address: http://ifeve.com/channels/
Statement: The Java NIO series of textbooks is not my original, only because after reading the original feeling in the article of the exquisite, intended to share with you, therefore, this is the worst, forget the original author forgive me. Also attached is the original address.
Java NiO channels are similar to streams, but are somewhat different:
-
- The data can be read from the channel, and the data can be written to the channel. But stream reads and writes are usually one-way.
- Channels can be read and written asynchronously.
- The data in the channel is always read to a buffer first, or it is always written from a buffer.
As mentioned above, the data is read from the channel to the buffer, and the data is written from the buffer to the channel. As shown in the following:
The implementation of channel
These are the most important implementations of the channel in Java NIO:
-
- FileChannel
- Datagramchannel
- Socketchannel
- Serversocketchannel
FileChannel read and write data from a file.
Datagramchannel can read and write data on the network through UDP.
Socketchannel can read and write data in the network via TCP.
Serversocketchannel can listen for incoming TCP connections, like a Web server. A socketchannel is created for each new incoming connection.
Basic Channel Example
The following is an example of using FileChannel to read data into buffer:
1Randomaccessfile Afile =NewRandomaccessfile ("Data/nio-data.txt", "RW");2FileChannel Inchannel =Afile.getchannel ();3 4Bytebuffer buf = Bytebuffer.allocate (48);5 6 intBytesread =Inchannel.read (BUF);7 while(Bytesread! =-1) {8 9System.out.println ("Read" +bytesread);Ten Buf.flip (); One A while(Buf.hasremaining ()) { -System.out.print ((Char) Buf.get ()); - } the - buf.clear (); -Bytesread =Inchannel.read (BUF); - } +Afile.close ();
Note that the call to Buf.flip () first reads the data into buffer, then inverts the buffer, and then reads the data from buffer. Further details of the buffer are explained in the next section.
Java NiO Series Tutorial (II.) Channel