Java NIO Channels are similar to streams with a few differences:
As mentioned above, you read data from a channel into a buffer, and write data from a buffer into a channel. Here is an illustration of that:
Java NIO: Channels read data into Buffers, and Buffers write data into Channels
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.
The ServerSocketChannel
allows you to listen for incoming TCP connections, like a web server does. For each incoming connection aSocketChannel
is created.
Here is a basic example that uses a FileChannel
to read some data into aBuffer
:
import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class FileChannelReadDataToBuffer { public static void main(String[] args) throws IOException { RandomAccessFile aFile = new RandomAccessFile("/home/kylin/work/tmp/tmp", "rw"); FileChannel inChannel = aFile.getChannel(); ByteBuffer buf = ByteBuffer.allocate(128); 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(); System.out.println(); bytesRead = inChannel.read(buf); } aFile.close(); } }
Notice the buf.flip()
call. First you read into a Buffer. Then you flip it. Then you read out of it. I'll get into more detail about that in the next text aboutBuffer
's.
本文转自:http://tutorials.jenkov.com/java-nio/channels.html