The advent of Java NiO is designed to improve the read and write speed of files, of course IO is re-implemented with NIO, so we do not have to show the call NiO can also enjoy this efficient file read and write.
Java NiO is highly efficient thanks to its two "assistants": Channel (pipeline) and buffer (buffer). Of course, these two "right-hand" age is much bigger than Java! To explain the knowledge to everyone in a simple and understandable way, let me give you an example of how this "two-dollar General" works with Java NiO.
There is a traditional smoking apparatus---hookahs in ancient China. I want to use this to simulate how channel and buffer work. Do not seek to say well, strive for accuracy.
Analyze how the Hookahs works:
The first step is to prepare for the finest cut tobacco; the second step is to fill the "bucket" with the appropriate amount of water, filling the tobacco silo with tobacco and inserting it into the water bucket, and then inserting the pipe into the water bucket; The third step is to light the tobacco and inhale. Cigarettes are generated from the smoke bin and filtered into the idle area of the water through water filtration. Fourth step, enjoy the thrill of smoking ..... From this example, we extract the main object "smoke" to analyze its motion trajectory. The smoke silo produces the smoke, passes through the water to the idle area above the water, then enters the human body through the smoke tube.
If the process above is understood and understood, then Java NiO you already know 50%, at least you already know how it works. Because the data treated with NIO is similar to smoking in water yandai. Let's analyze how NIO works, very simple.
Of course, like smoking. We must first have the desire to use NIO to deal with demand (which is like you want to smoke), for example I want to back up the Wk.txt file under C, the name of the backup file is Wk-bak.txt. Analogy with the process of just smoking:
Step one: Prepare, determine the location of the file, and convert files that are not directly manipulated by the program into the form of a character stream (this step is no different from the first step on the smoking example above, just doing some simple preparation).
String inFile = "C:\\wk.txt";
String outFile = "C:\\wk-bak.txt";
FileInputStream inf = new FileInputStream (inFile);
FileOutputStream Outf = new FileOutputStream (outFile);
Bytebuffer buffer = bytebuffer.allocate (1024);
Step Two: Create a file input pipeline, and a file output pipeline. (This step is slightly different from the second part of smoking on the top because the channel and buffer are "connection" actions that occur when reading and writing)
Prepare the file to read the pipe--the equivalent of a smoke bin and a smoke pipe
FileChannel INFC = Inf.getchannel ();
FileChannel OUTFC = Outf.getchannel ();
Charset Charset = Charset.forname ("Utf-8");
Encode and decode--equivalent to the water in the bucket water filtration effect
Charsetdecoder decoder = Charset.newdecoder ();
Charsetencoder encoder = Charset.newencoder ();
Step three: Start the file backup work.
while (true) {
Ready to write data to buffer--equivalent to igniting a cut of tobacco, with only the East wind
Buffer.clear ();
Character encoding--equivalent to the water filtration effect
Charbuffer cb = decoder.decode (buffer);
Bytebuffer BB = Encoder.encode (CB);
Data is encoded and then staged buffer-equivalent to water-filtered smoke suspended in the water bucket
int t = infc.read (BB);
if (t = =-1) {
Break
}
Bb.flip ();
Writes bytecode to the target file--the equivalent of the smoke has entered the mouth
Outfc.write (BB);
}
Step four: Check if the file is backed up successfully. Found under the C-disk more than a wk-bak.txt file, the content and wk.txt a touch. Then enjoy the pleasure that Java brings to you ....
The above example is estimated to have been understood almost, of course, if there will be some less appropriate, but not serious, the purpose is to learn nio, not smoking. If it feels like you can. then please add the above example complete, run it, enjoy the mighty NiO (of course, the character encoding is not necessary, just let this example appear to be complete a bit).
Well, if you understand the above, and really fill in the file backup of the small program, then to a little more in-depth study it.
I mentioned above that the example of smoking is not appropriate, one of which is that the internal mechanism of buffer and the simple filter function of the "water bucket" are different. and the character code. That piece is not something that's implemented inside buffer, decoder and encoder are two tools for buffer. Then we will analyze the buffer internal mechanism is not exactly the same where (the main analysis of the two commonly used methods; clear (), flip ())?
Come on, open the source of the buffer (extract the useful parts):
Public abstract class Buffer {
Invariants:mark <= Position <= limit <= capacity
private int mark =-1;
private int position = 0;
private int limit;
private int capacity;
Public final Buffer Clear () {
Position = 0;
Limit = capacity;
Mark =-1;
return this;
}
Public final Buffer Flip () {
limit = position;
Position = 0;
Mark =-1;
return this;
}
First we need to make it clear that the so-called buffer is just an array of "multifunction". may not be reflected in this buffer class, but if we open the Bytebuffer source will have byte[] array, open Charbuffer source code will have char[] array. Because buffer is the parent of all buffers, he can't predict how many buffers there will be, so simply let the "sons" themselves achieve it.
Now that we know the buffer is a "multi-functional Array", then we use the form of drawing to analyze the buffer above the source code.
Let's say we define a 8-unit large buffer, such as (in fact, buffer is such a thing). Let's start by telling you the three important properties about the state of the buffer:
Capacity: The capacity of the buffer;
Limit: How much data the buffer can take out or how much capacity the buffer has to hold the data;
Position: the equivalent of a cursor that records where we begin to write data and where to begin reading it.
It is also said that flip () and clear () are two important methods of buffer, because their two methods determine whether the buffer can read and write properly.
The flip () method must be executed when we want to write data from a buffer, and we must first execute the clear () method when we want to read the data from the buffer.
When writing data to buffer for the first time, once the flip () method is executed, the structure of the buffer becomes this: the position points to the first No. 0 digits that can access the data, and the limit and capacity point to the highest bit.
If, for the first time, we write 3 units of data to buffer, we execute the flip () method again, and the structure of the buffer becomes the one shown. But after the makeover of flip () position always points to the first available position in buffer. So, where was position before the flip () method was executed? Very simple, point to the location of the last data.
When we want to read the data from buffer, the clear () method is executed, and the internal structure of the buffer is shown, position points to the first of the readable data, and the limit points to the position of the original position.
From the above pictures we can see: capacity represents the buffer capacity is constant, the difference between limit and position always indicates that buffer can always read the data, or buffer in the capacity to write data. Also position is always less than or equal to Limit,limit is always less than or equal to capacity.
In fact, we have found that NIO is not as complex as IO, because the decorator and adaptor patterns in Io do not make sense to us at any time, but we are familiar with the design of IO.
NIO also has a knowledge point is the non-blocking socket programming, here does not say, because more complex, but if we really understand the selector this dispatcher's work, then the non-blocking implementation mechanism we almost mastered, complex is the code above.
I'm talking about the Java NIO.