One 、 Basic concept description

1.1 I/O brief introduction

I/O I.e. input and output , It's an interface between the computer and the outside world .IO The actual theme of operation is the operating system . stay java Programming , It's usually handled in a stream way IO, be-all IO It's seen as a single byte move , adopt stream Objects move one byte at a time . flow IO Responsible for converting objects into bytes , And then convert to objects .

About Java IO Please refer to my other article for related knowledge :Java IO Detailed explanation

1.2 What is? NIO

NIO namely New IO, This library is in JDK1.4 It was introduced in China .NIO and IO Have the same function and purpose , But the implementation is different ,NIO The main use is block , therefore NIO Is more efficient than IO Much higher .

stay Java API Two sets of NIO, One is for Standard input and output NIO, The other is Network programming NIO, This article focuses on NIO, About network programming NIO Please see Java NIO Detailed explanation ( Two ).

1.3 Flow vs. block

NIO and IO The biggest difference is the way data is packaged and transmitted .IO In order to flow How to process data , and NIO In order to block How to process data .

Facing the flow Of IO Processing data one byte at a time , One input stream produces one byte , One output stream consumes one byte . It's very easy to create filters for streaming data , Link a few filters , So that the data processing is very convenient and simple , But stream oriented IO It's usually very slow .

Facing the block Of IO The system processes data in blocks . Each operation generates or consumes a block of data in one step . It's much faster by block than by stream , But block oriented IO Lack of stream oriented IO Elegance and simplicity .

Two 、NIO Basics

Buffer and Channel It's a standard. NIO The core object of ( The Internet NIO There's another one. Selector The core object , Please refer to Java NIO Detailed explanation ( Two )), Almost every IO They are used in all operations .

Channel It's right IO Simulation of midstream , Any source and destination data must pass through a Channel object . One Buffer It's essentially a container object , issue Channel All of the objects in must be placed in Buffer in ; alike , from Channel Any data that you read in must read Buffer in .

2.1 About Buffer

Buffer It's an object , It contains some data to be written or read out . stay NIO in , Data is put into buffer Object's , And in the IO in , Data is written or read directly to Stream Object's . Applications can't directly address Channel Read and write , And must pass Buffer To carry out , namely Channel It's through Buffer To read and write data .

stay NIO in , All the data is in Buffer To deal with the , It is NIO Transfer pool for reading and writing data .Buffer It's essentially an array , It's usually a byte of data , But it can also be other types of arrays . But a buffer is more than an array , What's important is that it provides structured access to data , It can also track the reading and writing process of the system .

Use Buffer Reading and writing data generally follows the following four steps :

  1. Write data to Buffer;
  2. call flip() Method ;
  3. from Buffer Read data from ;
  4. call clear() Methods or compact() Method .

Direction Buffer When writing data ,Buffer How much data has been written down . Once you want to read the data , Need to pass through flip() Methods will Buffer  Switch from write mode to read mode . In read mode , Can read before writing to Buffer All data for .

Once you've read all the data , You need to clear the buffer , Let it be written again . There are two ways to clear the buffer : call clear() or compact() Method .clear() Method will clear the entire buffer .compact() Method will only clear the data that has been read . Any unread data is moved to the beginning of the buffer , The newly written data will be placed behind the unread data in the buffer .

Buffer There are mainly the following :

2.3 About Channel

Channel It's an object , It can be used to read and write data . Think of it as IO Flow in . But it's a little bit different from streaming :

  1. Channel It's two-way , Can read and write , And the flow is unidirectional
  2. Channel It can read and write asynchronously
  3. Yes Channel You have to read and write through buffer object

As mentioned above , All data passed Buffer Object processing , therefore , You never write bytes directly to Channel in , contrary , You are writing data to Buffer in ; Again , And you won't come from Channel Read bytes in , It's about taking data from Channel Read in Buffer, Again from Buffer Get this byte .

because Channel It's two-way , therefore Channel It can better reflect the real situation of the underlying operating system than the flow . Especially in Unix In the model , The underlying operating system is usually bidirectional .

stay Java NIO in Channel There are mainly the following types :

  • FileChannel: Reading data from a file
  • DatagramChannel: Reading and writing UDP Network protocol data
  • SocketChannel: Reading and writing TCP Network protocol data
  • ServerSocketChannel: Can monitor TCP Connect

3、 ... and 、 From theory to practice :NIO Reading and writing in

IO Reading and writing in , Corresponding to data and Stream,NIO Reading and writing in , The corresponding is the channel and buffer .NIO Read from channel in : Create a buffer , Then let the channel read the data into the buffer .NIO Write data to channel : Create a buffer , Fill it with data , Then let the channel use the data to write .

3.1 Read from file

We already know , stay NIO In the system , Any time a read operation is performed , You are all from Channel Read from , And you're not directly from Channel Read data from , Because all the data has to be Buffer To encapsulate , So you should be from Channel Read data to Buffer.

therefore , If you read data from a file , There are three steps :

  1. from FileInputStream obtain Channel
  2. establish Buffer
  3. from Channel Read data to Buffer

Now let's take a look at the specific process : 
First step : Get access to

FileInputStream fin = new FileInputStream( "readandshow.txt" );
FileChannel fc = fin.getChannel();

The second step : Create buffer

ByteBuffer buffer = ByteBuffer.allocate( 1024 );

The third step : Read data from channel to buffer buffer );

3.2 Write data to file

It's like reading data from a file , 
First step : Get a channel

FileOutputStream fout = new FileOutputStream( "writesomebytes.txt" );
FileChannel fc = fout.getChannel();

The second step : Create buffer , Put the data into the buffer

ByteBuffer buffer = ByteBuffer.allocate( 1024 );

for (int i=0; i<message.length; ++i) {
buffer.put( message[i] );

The third step : Write buffer data to channel

fc.write( buffer );

3.3 Combination of reading and writing

CopyFile It's a very good example of a combination of reading and writing , We will pass CopyFile This strength makes you realize NIO Operation process .CopyFile Perform three basic operations : Create a Buffer, Then read the data from the source file to the buffer , Then write the buffer to the target file .

* use java NIO api Copy files
* @param src
* @param dst
* @throws IOException
public static void copyFileUseNIO(String src,String dst) throws IOException{
// Declare source and destination files
FileInputStream fi=new FileInputStream(new File(src));
FileOutputStream fo=new FileOutputStream(new File(dst));
// Get the transmission channel channel
FileChannel inChannel=fi.getChannel();
FileChannel outChannel=fo.getChannel();
// Get the container buffer
ByteBuffer buffer=ByteBuffer.allocate(1024);
// Decide if you have read the document
int eof;
// Reset it buffer Of position=0,limit=position
// Start writing
// Reset after writing buffer, reset position=0,limit=capacity

Four 、 Something to watch out for

There are three things to note in the above procedure

4.1 Check status

When there is no more data , Copy is complete , here read() Method will return -1 , We can judge whether we have finished reading according to this method .

int r= buffer );
if (r==-1) {

4.2 Buffer Class flip、clear Method

control buffer Three variables of state

  • position: Track how much data has been written or read , It points to where the next byte comes from
  • limit: Represents how much data can be retrieved or how much space can be written , Its value is less than or equal to capacity.
  • capacity: Represents the maximum size of the buffer , When creating a new buffer ,limit The value of and capacity The default value of is equal .

flip、clear These two methods are used to set these values .

flip Method

Let's take a look first flip Source code :

public final Buffer flip() {
limit = position;
position = 0;
mark = -1;
return this;

Above FileCopy In the program , Before we write the data, we call buffer.flip(); Method , This method takes the current pointer position position Set up a limit, And then the current pointer position Point to the beginning of the data , We can now write data from the buffer to the channel . position Set to 0, This means that the next byte we get is the first byte . limit Has been set to the original position, This means that it includes all bytes read before , And not a single byte .

clear Method

Have a look first clear Source code :

 public final Buffer clear() {
position = 0;
limit = capacity;
mark = -1;
return this;

Above FileCopy In the program , After writing data, before reading data , We call  buffer.clear(); Method , This method resets the buffer to receive more bytes . The figure above shows calling clear() Status of the back buffer .

Reprint please explain the source , Link to the original text :

Java IO--NIO( One ) More articles about

  1. Java IO/NIO course

    Java IO course Java NIO course English version : ...

  2. One article understands Java IO/NIO/AIO

      Catalog summary One .IO flow ( Sync . Blocking ) Two .NIO( Sync . Non blocking ) 3、 ... and .NIO2( asynchronous . Non blocking ) Text summary Before we learn Java Of IO Before flow , We all need to know a few key words Synchronous and asynchronous (synchronou ...

  3. Java IO NIO Explain in detail

    1.IO Java IO summary 2.NIO Java NIO elementary analysis

  4. java IO NIO BIO The most authoritative conclusion

    1. BIO (Blocking I/O) 1.1 Tradition BIO 1.2 Pseudo asynchrony IO 1.3 Code example 1.4 summary 2. NIO (New I/O) 2.1 NIO brief introduction 2.2 NIO Characteristics of /N ...

  5. Java IO : NIO And IO The difference between

    Reference material : NIO It's stream oriented ,IO It's buffer oriented . NIO It's non thread blocking ,IO It's thread blocking . NIO Of Selector ...

  6. java IO Nio File copy tool class Files

    public static void main(String[] args) throws Exception { Files.copy(Paths.get("file/text.txt&q ...

  7. JAVA IO NIO ...

  8. Java IO With Network Programming Notes

    <!doctype html>Java IO&NIO figure:first-child { margin-top: -20px; } #write ol, #write ul ...

  9. Java in NIO And IO The difference between

    When learning Java NIO and IO Of API after , A question immediately came to mind : When should I use IO, When to use NIO Well ? In this paper , I'll try to be as clear as I can Java NIO and IO The difference of . Their usage scenarios , And how they affect your generation ...

  10. JAVA IO as well as NIO understand

    because Netty, I learned something about asynchrony IO Knowledge ,JAVA Inside NIO It's the original IO A supplement to , This paper is mainly recorded in JAVA in IO The underlying implementation principle of , And right Zerocopy Technology is introduced . IO, It actually means : Data keeps moving in and out ...

Random recommendation

  1. C++ and C How the functions in call each other

    A question I met in today's written test , At that time, it was written to declare in front of the function as C, Press C compile . The first is C Call in C++ function , Including ordinary functions , Overloaded functions and member functions . For ordinary functions , stay C++ Declared as extern "C", stay ...

  2. Use redis-dump Conduct Redis Database merge

    Preface When processing data recently , It's about cross server access , I have two Redis The servers are on different machines , It brings a lot of inconvenience to data maintenance , So I studied how to combine the two Redis The data in is merged into one place . I searched some tools from the website , eureka ...

  3. CSE(Corrupted State Exceptions) Serious exception handling method

    Cause analysis This problem shows that .NET The version is at least 4.0, Because Microsoft is .NET 4.0 Exception handling mechanism changed in version . Microsoft thinks catch(Exception) This kind of writing is irresponsible , The programmer should determine the program according to the severity of the exception ...

  4. [C++]VS Download with third party tools

    name :Qt 5.1.1 ( Commercial and open source license GPL/LGPL) explain :Qt It's a 1991 Cross platform developed by Qiqu technology in C++ GUI application development framework download : ...

  5. Actually H5 That's how it's made ~

    Today's H5 The technology is getting more and more mature ,H5 It's getting easier to make , In especial H5 Production tools ( field , Basically, a relatively complete industrial chain has been formed , So for today's enterprises , If you haven't experienced it yet ...

  6. Apache、Tomcat、JBoss、WebLogic The difference and relationship between

    Weblogic: It's an enterprise class application server , These include j2ee All kinds of applications such as jsp,servlet,ejb etc. Tomcat:   It's a rudimentary application server , Support sp and servlet, I won't support it EJB, If you need E ...

  7. [ turn ]ARM/Thumb/Thumb-2

    ref: A few months ago I gave a presentatio ...

  8. utilize socket The module checks for port survivals and email alerts

    It can be used to monitor some ports . import socket def check_server(addr, port): s = socket.socket() try: s.connect((addr, po ...

  9. VIM Character encoding settings for

    vim The encoding settings are the same as all popular text editors ,Vim You can edit all kinds of character coding files very well , That includes, of course UCS-2.UTF-8 Popular. Unicode Encoding mode . unfortunately , And a lot from Linux ...

  10. MeshRenderer Components and related API

    MeshRenderer: Grid filter , be used for " Rendering " According to the model . Cast Shodows: Whether to cast shadows .(on: open .off: Turn off ) Receive Shodows: Whether to receive shadows . Ma ...