Java Advanced------Java NIO

Source: Internet
Author: User

Introduction to Java NIOI/O

I/O or input and output refers to the interface between the computer and the outside world or between a program and the rest of the computer. It is critical for any computer system, so the body of all I/O is actually built into the operating system. Separate programs generally allow the system to do most of the work for them.

In Java programming, I/O has been completed until recently using a stream. All I/O is treated as a single byte movement, moving one byte at a time through an object called stream. Flow I/O is used to contact the outside world. It is also used internally to convert an object to a byte and then back to the object.

NIO has the same effect and purpose as the original I/O, but it uses a different approach: block I/O, which is much more efficient than stream I/O.

Why do you use NIO?

NiO was created to enable Java programmers to implement high-speed I/O without having to write custom native code. NiO transfers the most time-consuming I/O operations (that is, the fill and fetch buffers) back to the operating system, which can greatly improve speed.

Flow vs. block comparison

The most important difference between the original I/O library and NiO is the way data is packaged and transmitted. As mentioned earlier, the original I/O processes the data in a streaming way, and NIO processes the data in chunks.

Stream-oriented I/O

The system processes data one byte at a time, one input stream produces one byte of data, and one output stream consumes one byte of data. Creating filters for streaming data can be very easy. Link several filters so that each filter is only part of a single complex processing mechanism. The downside, however, is that stream-oriented I/O is usually quite slow.

Block-oriented I/O

The system processes the data as a block. Each operation produces or consumes a block of data in one step, and processing the data in chunks is much faster than streaming the data in the same way. But relatively speaking, no flow-oriented I/O is straightforward.

Channels and buffers

Channels and buffers are the core objects in NiO and are used mttud every I/O operation.
A channel is a stream of analog to the original I/O package, and all data from any destination or anywhere must pass through a channel object. A buffer object is essentially a container object, and all objects sent to a channel must first be placed in the buffer, and any data read from the channel will be read into the buffer as well.

Buffer

A buffer is essentially an array. Usually it is a byte array, but you can use other kinds of arrays as well. But a buffer is not just an array, it also provides structured access to the data, and can also track the read and write processes of the system.

Buffer type
    • Bytebuffer
    • Charbuffer
    • Intbuffer
    • Longbuffer
    • Floatbuffer
    • DoubleBuffer

Each of the buffer classes is an instance of the buffer interface. In addition to Bytebuffer, each buffer class has exactly the same operation, except that they handle a different type of data because most standard I/O operations use Bytebuffer, so it has all the shared buffer operations and some unique operations.

Channel

A channel is an object through which data can be read or written. As previously mentioned, all data is handled through the buffer object. You never write bytes directly into the channel, instead, you write the data to a buffer that contains one or more bytes. Again, instead of reading the bytes directly from the channel, you read the data into the buffer and read the byte from the buffer.

Channel type

The difference between a channel and a stream is that the channel is bidirectional, and the stream is moved only in one direction, and through it can be used for reading, writing, or concurrently reading and writing.

Read and write in NiO

Read-write is the basic process of I/O. Reading from one channel is simple: just create a buffer and let the channel read the data into this buffer. Writing is also simple: Create a buffer, populate it with data, and let the channel use that data to perform write operations.

Read from File

There are three steps involved in reading a file:

    • 1 Getting Channel
RandomAccessFile aFile = new RandomAccessFile("testNIO.in""rw"inChannel = aFile.getChannel();
    • 2 Creating a buffer
ByteBuffer buf = ByteBuffer.allocate(48);
    • 3 reading data from the channel to buffer
inChannel.read(buf);

You might notice that we don't have to tell the channel how much data to read into the buffer, each buffer has a complex internal statistical mechanism that tracks how much data has been read and how much more space can hold more data.

Write file

Writing a file in NiO is similar to reading from a file, first or the channel is obtained.

new RandomAccessFile("testNIO1.out""rw");FileChannel outChannel = toFile.getChannel();

The buffer is then created and the data is written to the buffer.

"New String to write to File!";ByteBuffer buf = ByteBuffer.allocate(50);buf.clear();buf.put(newData.getBytes());buf.flip();

Finally, the content in the buffer is written to the channel.

toChannel.write(buf);

Here again, there is no need to tell the channel how much data to write.

Read-write combination

Here is an example of a read-write combination that copies the contents of one file into another, as well as three basic operations:

    • 1 Creating a buffer
ByteBuffer buf = ByteBuffer.allocate(50);
    • 2 reading data from the source file into this buffer
inChannel.read(buf);
    • 3 Writing the data in the buffer to the destination file
outChannel.write(buf);

Note that this process repeatedly reads, writes, reads, and writes until the source file ends.

Channel transfer

The above example gives the general idea of copying files, in fact, if it is FileChannel, you can also use the Transferfrom () and Transferto () method to complete the file copy. The use of these two methods is given directly below:

    /** * FileChannel's Transferfrom () method can transfer data from the source channel to the FileChannel */    Private void Channeltransferfrom() {Try{Randomaccessfile FromFile =NewRandomaccessfile ("Testnio1.in","RW");            FileChannel Inchannel = Fromfile.getchannel (); Randomaccessfile ToFile =NewRandomaccessfile ("Testnio1.out","RW"); FileChannel Outchannel = Tofile.getchannel ();LongPosition =0;LongCount = Inchannel.size ();            Outchannel.transferfrom (Inchannel, position, count);            Fromfile.close ();        Tofile.close (); }Catch(FileNotFoundException e) {//TODO auto-generated catch blockE.printstacktrace (); }Catch(IOException e) {//TODO auto-generated catch blockE.printstacktrace (); }    }/** * TransferTo () method transfers data from FileChannel to other channel */    Private void Channeltransferto() {Try{Randomaccessfile FromFile =NewRandomaccessfile ("Testnio2.in","RW");            FileChannel Inchannel = Fromfile.getchannel (); Randomaccessfile ToFile =NewRandomaccessfile ("Testnio2.out","RW"); FileChannel Outchannel = Tofile.getchannel ();LongPosition =0;LongCount = Inchannel.size ();            Inchannel.transferto (position, count, Outchannel);            Fromfile.close ();        Tofile.close (); }Catch(FileNotFoundException e) {//TODO auto-generated catch blockE.printstacktrace (); }Catch(IOException e) {//TODO auto-generated catch blockE.printstacktrace (); }    }

You can see that the usage of two methods is very similar.

Here are just a few of the basics of nio that need to be understood in depth: http://ifeve.com/overview/
All the code involved in this article:

 PackageCom.jesson.mianshi.nio;ImportJava.io.FileNotFoundException;ImportJava.io.IOException;ImportJava.io.RandomAccessFile;ImportJava.nio.ByteBuffer;ImportJava.nio.channels.FileChannel; Public  class niodemo {    /** * @param args * *     Public Static void Main(string[] args) {//TODO auto-generated method stubNiodemo nd =NewNiodemo ();//Nd.filechannelread ();        //Nd.filechannelwrite ();        //Nd.channeltransferfrom ();        //Nd.channeltransferto ();Nd.copyfile (); }/** * NIO Read */    Private void Filechannelread() {Try{Randomaccessfile Afile =NewRandomaccessfile ("Testnio.in","RW");            FileChannel Inchannel = Afile.getchannel (); Bytebuffer buf = Bytebuffer.allocate ( -);intByteread = Inchannel.read (BUF); while(Byteread! =-1) {System.out.println ("Read"+ Byteread); Buf.flip (); while(Buf.hasremaining ()) {System.out.print (Char) Buf.get ());                } buf.clear ();                Byteread = Inchannel.read (BUF); System.out.println ("\ n"+ Byteread);        } afile.close (); }Catch(FileNotFoundException e) {//TODO auto-generated catch blockE.printstacktrace (); }Catch(IOException e) {//TODO auto-generated catch blockE.printstacktrace (); }    }/** * Write data to FileChannel * /    Private void Filechannelwrite() {String NewData ="New String to write to file!"; Randomaccessfile ToFile =NULL;Try{ToFile =NewRandomaccessfile ("Testnio.out","RW"); }Catch(FileNotFoundException e) {//TODO auto-generated catch blockE.printstacktrace ();        } FileChannel Tochannel = Tofile.getchannel (); Bytebuffer buf = Bytebuffer.allocate ( -);        Buf.clear ();        Buf.put (Newdata.getbytes ()); Buf.flip (); while(Buf.hasremaining ()) {Try{Tochannel.write (BUF); }Catch(IOException e) {//TODO auto-generated catch blockE.printstacktrace (); }        }Try{Tofile.close (); }Catch(IOException e) {//TODO auto-generated catch blockE.printstacktrace (); }    }/** * FileChannel's Transferfrom () method can transfer data from the source channel to the FileChannel */    Private void Channeltransferfrom() {Try{Randomaccessfile FromFile =NewRandomaccessfile ("Testnio1.in","RW");            FileChannel Inchannel = Fromfile.getchannel (); Randomaccessfile ToFile =NewRandomaccessfile ("Testnio1.out","RW"); FileChannel Outchannel = Tofile.getchannel ();LongPosition =0;LongCount = Inchannel.size ();            Outchannel.transferfrom (Inchannel, position, count);            Fromfile.close ();        Tofile.close (); }Catch(FileNotFoundException e) {//TODO auto-generated catch blockE.printstacktrace (); }Catch(IOException e) {//TODO auto-generated catch blockE.printstacktrace (); }    }/** * TransferTo () method transfers data from FileChannel to other channel */    Private void Channeltransferto() {Try{Randomaccessfile FromFile =NewRandomaccessfile ("Testnio2.in","RW");            FileChannel Inchannel = Fromfile.getchannel (); Randomaccessfile ToFile =NewRandomaccessfile ("Testnio2.out","RW"); FileChannel Outchannel = Tofile.getchannel ();LongPosition =0;LongCount = Inchannel.size ();            Inchannel.transferto (position, count, Outchannel);            Fromfile.close ();        Tofile.close (); }Catch(FileNotFoundException e) {//TODO auto-generated catch blockE.printstacktrace (); }Catch(IOException e) {//TODO auto-generated catch blockE.printstacktrace (); }    }/** * Copy files * /    Private void CopyFile() {Try{Bytebuffer buf = bytebuffer.allocate ( -); Randomaccessfile FromFile =NewRandomaccessfile ("Testnio3.in","RW");            FileChannel Inchannel = Fromfile.getchannel (); Randomaccessfile ToFile =NewRandomaccessfile ("Testnio3.out","RW"); FileChannel Outchannel = Tofile.getchannel ();intByteread = Inchannel.read (BUF); while(Byteread! =-1) {Buf.flip ();                Outchannel.write (BUF);                Buf.clear ();            Byteread = Inchannel.read (BUF);            } fromfile.close ();        Tofile.close (); }Catch(FileNotFoundException e) {//TODO auto-generated catch blockE.printstacktrace (); }Catch(IOException e) {//TODO auto-generated catch blockE.printstacktrace (); }    }}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java Advanced------Java NIO

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.