Java NIO Channel
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.
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
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
Here is a basic example, uses a to FileChannel read some data into a Buffer :
randomaccessfile afile = new randomaccessfile ("Data/nio-data.txt", "RW" Span style= "color: #000000"); FileChannel inchannel = Afile.getchannel (); Bytebuffer buf = bytebuffer.allocate (48 int bytesread = Inchannel.read (BUF); while (bytesread! = -1 "Read" + bytesread); Buf.flip (); while (buf.hasremaining ()) { System.out.print (( char = Inchannel.read (BUF); } afile.close ();
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 (2) Channel