One: Java's NIO channel
Java NiO channels are similar to streams, but are somewhat different:
The ==> can read data from the channel and write data to the channel. But stream reads and writes are usually one-way.
==> channels can be read and written asynchronously.
The data in the ==> channel is always read to a buffer first, or it is always written from a buffer.
As mentioned above, the data is read from the channel to the buffer, and the data is written from the buffer to the channel. As shown in the following:
Second: implementation of the channel of NiO in Java
These are the most important implementations of the channel in Java NIO:
==>filechannel:
==>datagramchannel
==>socketchannel
==>serversocketchannel
Third: The role of the implementation of the Java NIO Channel
==>filechannel Read and write data from a file.
==>datagramchannel can read and write data on the network through UDP.
==>socketchannel can read and write data in the network via TCP.
==>serversocketchannel can listen for incoming TCP connections, like a Web server. A socketchannel is created for each new incoming connection.
Four: A basic example of a Java NIO channel
1 PackageCom.yeepay.sxf.testnio;2 3 Importjava.io.IOException;4 ImportJava.io.RandomAccessFile;5 ImportJava.nio.ByteBuffer;6 ImportJava.nio.channels.FileChannel;7 /**8 * Simple test of the role of channel components in the Java NiO9 * @authorSXFTen * One */ A Public classTestchannelfornio { - - Public Static voidMain (string[] args)throwsIOException { the //loading files into memory/usr/sxf/testnio file -Randomaccessfile Afile =NewRandomaccessfile ("/usr/sxf/testnio", "RW"); - //get the channel from the file -FileChannel Inchannel =Afile.getchannel (); + //registers a buffer from the channel, 48 bytes at a time -Bytebuffer buf = Bytebuffer.allocate (48); + //Read the first time A intBytesread =Inchannel.read (BUF); at //See if there's any data in the file - while(Bytesread! =-1) { - //print the number of characters that are read for the first time -System.out.println ("Read" +bytesread); - - //Note that the call to Buf.flip () first reads the data into buffer, then inverts the buffer, and then reads the data from buffer. in Buf.flip (); - to //print each character to a console + while(Buf.hasremaining ()) { -System.out.print ((Char) Buf.get ()); the } * $ //clear this buffer .Panax Notoginseng buf.clear (); - theBytesread =Inchannel.read (BUF); + A } the + afile.close (); - } $}
View Code
Java NIO: The concept of the channel of the NIO series tutorial in Java