Java NIO Channel
- Channel implementations
- Basic Channel Example
|
Jakob Jenkov
Last update:2014-06-23 |
Java NIO Channels is similar to streams with a few differences:
- You can both read and write to a Channels. Streams is typically one-way (read or write).
- Channels can be read and written asynchronously.
- Channels always read to, or write from, a Buffer.
NiO can be read and written, stream can only read or write
The channel can read and write asynchronously
The channel reads buffer and writes from buffer to channel
As mentioned above, you read the data from a channel to a buffer, and write data from a buffer into a channel. Here is a illustration of that:
|
| Java nio:channels read data into buffers, and buffers write data into Channels |
Channel implementations
Some implementation classes of channel
Here is the most important Channel implementations in Java NIO:
- FileChannel
- Datagramchannel
- Socketchannel
- Serversocketchannel
The FileChannel reads data from and to files.
The DatagramChannel can read and write data over the network via UDP.
The SocketChannel can read and write data over the network via TCP.
ServerSocketChannelthe allows listen for incoming TCP connections, like a Web server does. For each incoming connection A is SocketChannel created.
Basic Channel Example
An example of a channel
Here is a basic example, uses a to FileChannel read some data into a 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 ();
Notice the flip () method, which starts by reading buffer and then calling Flip () to read something out of the buffer.
Notice the call buf.flip() . First you read to a Buffer. Then you flip it. Then you read out of it. I'll get into more detail on the next text about Buffer ' s.
Java NIO Channel