Java NIO channels are similar to streams, but are somewhat different:
You can both read data from the channel and write data to the channel. But reading and writing streams are usually one-way.
Channels can be read and written asynchronously.
The data in the channel must first be read into a Buffer, or always written from a Buffer.
As mentioned above, data is read from the channel to the buffer and data is written from the buffer to the channel. As shown in the figure below:
These are the implementations of the most important channels in Java NIO:
FileChannel
DatagramChannel
SocketChannel
ServerSocketChannel
FileChannel reads and writes data from files.
DatagramChannel can read and write data in the network through UDP.
SocketChannel can read and write data in the network through TCP.
ServerSocketChannel can monitor new incoming TCP connections, like a web server. A SocketChannel is created for each new incoming connection.
The following is an example of using FileChannel to read 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();
Pay attention to the call of buf.flip(), read the data first to the Buffer, then reverse the Buffer, and then read data from the Buffer. The next section will go into more details about Buffer.
Related articles:
Java NIO Series Tutorial 1: A brief introduction to Java NIO
Java NIO Series Tutorial 3: Basic usage of Buffer
Related videos:
Illustration of JDK download process-JAVA beginner video tutorial
The above is the detailed content of Java NIO series tutorial 2: Java NIO channels are similar to streams. For more information, please follow other related articles on the PHP Chinese website!