Defined by the Java.nio.channels package, the channel represents the connection between the IO source and the target, and the channel is similar to the traditional "stream", except that the channel itself cannot directly access the data, and the channel can only interact with buffer. Channels are primarily used to transfer data from one side of the buffer to an entity on the other side (such as files, sockets ...). ), and vice versa; the channel is the conduit that accesses the IO service, through which we can access the operating system's I/O services with minimal overhead; by the way, buffers are the endpoints that send data and receive data inside the channel.
In the standard IO, it is based on the byte stream/character stream, while in NiO it is based on channel and buffer operation, in which the channel, although simulating the concept of flow, but actually very different.
difference |
Stream |
Channel |
Supports asynchronous |
Not supported |
Support |
Whether data can be transmitted in two directions |
No, only one way |
Yes, you can read data from the channel or write to the channel |
Whether to use with buffer |
No |
Must be used in conjunction with buffer |
Performance |
Lower |
Higher |
The early generation IO operation is the CPU responsible for the IO interface:
New Generation DMA Authorization processing IO interface:
Channel mode:
- How to obtain the channel:
Java.nio.channels.Channel Interface:
|--filechannel
|--socketchannel
|--serversocketchannel
|--datagramchannel
Ways to get channels
1) Java provides a Getchannel () method for a class that supports channels
Local IO:
|--fileinputstream/fileoutputstream
|--randomaccessfile
Network IO:
|--socket
|--serversocket
|--datagramsocket
|--pip.***
2) The nio.2 in JDK1.7 provides a static method for each pass open ()
3) Newbytechannel () of the Files tool class of nio.2 in JDK1.7
4) static method Newchannel () is provided in the Channles tool class.
Java-nio (iv): Principle and acquisition of channels (channel)