Java Nio
1 |
Java NIO Tutorial |
2 |
Java NIO Overview |
3 |
Java NIO Channel |
4 |
Java NIO Buffer |
5 |
Java NIO Scatter/gather |
6 |
Java NIO Channel to channel transfers |
7 |
Java NIO Selector |
8 |
Java NIO FileChannel |
9 |
Java NIO Socketchannel |
10 |
Java NIO Serversocketchannel |
11 |
Java NIO Datagramchannel |
12 |
Java NIO Pipe |
13 |
Java NIO vs. IO |
Java NIO Channel
by Jakob JenkovConnect with me:
Rate article: Share Article:tweet
Table of Contents
- Channel implementations
- Basic Channel Example
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.
ServerSocketChannel
the 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"); FileChannel Inchannel = Afile.getchannel (); Bytebuffer buf = Bytebuffer.allocate (48); 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 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.
Next: Java NIO Buffer
Java NIO Channel