Home > Java > javaTutorial > body text

Java NIO series tutorial 2: Java NIO channels are similar to streams

php是最好的语言
Release: 2018-07-30 10:39:53
Original
1660 people have browsed it

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:

Channel implementation

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.

Basic Channel Example

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();
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!