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:
Randomaccessfile afile = new Randomaccessfile ("Data/nio-data.txt", "RW"); FileChannel Inchannel = Afile.getchannel (); Bytebuffer buf = bytebuffer.allocate; 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 ();
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