Java advanced ------ Java NIO

Source: Internet
Author: User

Java advanced ------ Java NIO
Introduction to Java NIOI/O

I/O or input/output refers to the interface between the computer and the external world or between a program and the rest of the computer. It is critical to any computer system, so all I/O entities are actually built in the operating system. A separate program generally allows the system to do most of the work for them.

In Java programming, I/O has been completed using the stream method until recently. All I/O operations are regarded as the movement of a single byte, and one byte is moved at a time through an object called Stream. Stream I/O is used to contact the external world. It is also used internally to convert an object into bytes and then convert it back to an object.

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

Why NIO?

NIO is created to enable java programmers to achieve high-speed I/O without writing custom local code. NIO transfers the most time-consuming I/O operations (that is, the filling and extraction buffer) back to the operating system, thus greatly improving the speed.

Stream and block comparison

The most important difference between the original I/O database and NIO is the data packaging and transmission mode. As mentioned above, the original I/O processes data in a stream, while NIO processes data in blocks.

Stream-oriented I/O

The system processes data in one byte at a time. An input stream generates one byte of data and an output stream consumes one byte of data. It is very easy to create filters for streaming data. Links several filters so that each filter is only part of a single complex processing mechanism. However, the disadvantage is that stream-oriented I/O is usually quite slow.

Block-oriented I/O

The system processes data in blocks. Each operation generates or consumes a data block in one step. Data Processing by block is much faster than data processing by streaming. However, it is relatively easy to face stream I/O.

Channels and Buffers

Channels and buffers are the core objects in NIO. They are used in each I/O operation of mttud.
A Channel is a simulation of the flow in the original I/O package. All data to any destination or from any place must pass through a Channel object. A Buffer object is essentially a container object. All objects sent to a channel must first be placed in the Buffer. Similarly, any data read from the channel must be read to the Buffer.

Buffer Zone

The buffer is essentially an array. It is usually a byte array, but other types of arrays can also be used. However, a buffer zone is not just an array, it also provides structured access to data, and can also track system read/write processes.

Buffer type ByteBuffer CharBuffer IntBuffer LongBuffer FloatBuffer DoubleBuffer

Each Buffer class is an instance of the Buffer interface. Except for ByteBuffer, each Buffer class has the same operation, but they process different data types, because most standard I/O operations require ByteBuffer, therefore, it has all the shared buffer operations and some special operations.

Channel

A channel is an object that can be used to read or write data. As mentioned above, all data is processed through the Buffer object. You will never write bytes directly into the channel. Instead, you write data into a buffer that contains one or more bytes. Similarly, you will not directly read the byte from the channel, but read the data to the buffer and then 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 only moving in one direction. It can be used for reading, writing, or reading and writing at the same time.

Read/write in NIO

Read/write is the basic process of I/O. Reading from a channel is simple: you only need to create a buffer and then let the channel read data to this buffer. Writing is also simple: create a buffer, fill it with data, and then let the channel use the data to perform the write operation.

Read from File

Reading a file involves three steps:

1. Obtain the Channel
RandomAccessFile aFile = new RandomAccessFile(testNIO.in, rw);FileChannel inChannel = aFile.getChannel();
2 create a Buffer
ByteBuffer buf = ByteBuffer.allocate(48);
3. read data from the Channel to the Buffer
inChannel.read(buf);

You may notice that we do not need to tell the channel how much data to read to the buffer zone. Each buffer zone has a complex internal statistical mechanism, it will track how much data has been read and how much space can accommodate more data.

Write files

Writing a file to NIO is similar to reading from a file. First, you can obtain a channel.

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

Create a buffer and write the data into the buffer.

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

The last step is to write the content in the buffer to the channel.

toChannel.write(buf);

Similarly, you do not need to tell the channel how much data to write.

Read/write Integration

The following is an example of a combination of reading and writing. The purpose is to copy the content of a file to another file, which is also divided into three basic operations:

1. Create a Buffer
ByteBuffer buf = ByteBuffer.allocate(50);
2. read data from the source file to the buffer.
inChannel.read(buf);
3. Write Data in the buffer to the target file.
outChannel.write(buf);

Note that this process continues to read, write, read, and write until the source file ends.

Channel Transfer

The above example shows the idea of copying files. In fact, if it is FileChannel, you can also use the transferFrom () and transferTo () Methods to copy files. The following describes the usage of the two methods:

/*** The transferFrom () method of FileChannel can transmit data from the source channel to FileChannel */private void channelTransferFrom () {try {RandomAccessFile fromFile = new RandomAccessFile (testNIO1.in, rw); FileChannel inChannel = fromFile. getChannel (); RandomAccessFile toFile = new RandomAccessFile (testNIO1.out, rw); FileChannel outChannel = toFile. getChannel (); long position = 0; long count = inChannel. size (); outChannel. transferFrom (inChannel, position, count); fromFile. close (); toFile. close ();} catch (FileNotFoundException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace () ;}}/*** transfer data from FileChannel to another channel */private void channelTransferTo () {try {RandomAccessFile fromFile = new RandomAccessFile (testNIO2.in, rw); FileChannel inChannel = fromFile. getChannel (); RandomAccessFile toFile = new RandomAccessFile (testNIO2.out, rw); FileChannel outChannel = toFile. getChannel (); long position = 0; long count = inChannel. size (); inChannel. transferTo (position, count, outChannel); fromFile. close (); toFile. close ();} catch (FileNotFoundException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();}}

The usage of the two methods is extremely similar.

Here is just to give some of the basis of NIO, you need to have a deep understanding of can see: http://ifeve.com/overview/
All the Code involved in this article:

Package com. jesson. mianshi. nio; import java. io. fileNotFoundException; import java. io. IOException; import java. io. randomAccessFile; import java. nio. byteBuffer; import java. nio. channels. fileChannel; public class NIODemo {/*** @ param args */public static void main (String [] args) {// TODO Auto-generated method stub NIODemo nd = new NIODemo (); // nd. fileChannelRead (); // nd. fileChannelWrite (); // nd. chann ElTransferFrom (); // nd. channelTransferTo (); nd. copyFile ();}/*** NIO read */private void fileChannelRead () {try {RandomAccessFile aFile = new RandomAccessFile (testNIO. in, rw); FileChannel inChannel = aFile. getChannel (); ByteBuffer buf = ByteBuffer. allocate (48); int byteRead = 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 (+ byteRead);} aFile. close ();} catch (FileNotFoundException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();}}/** * Write data to FileChannel */private void fileChannelWrite () {String newData = New String to write to File !; RandomAccessFile toFile = null; try {toFile = new RandomAccessFile (testNIO. out, rw);} catch (FileNotFoundException e) {// TODO Auto-generated catch block e. printStackTrace ();} FileChannel toChannel = toFile. getChannel (); ByteBuffer buf = ByteBuffer. allocate (50); buf. clear (); buf. put (newData. getBytes (); buf. flip (); while (buf. hasRemaining () {try {toChannel. write (buf);} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace () ;}try {toFile. close ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace () ;}/ *** the transferFrom () method of FileChannel can transmit data from the source channel to FileChannel */private void channelTransferFrom () {try {RandomAccessFile fromFile = new RandomAccessFile (testNIO1.in, rw); FileChannel inChannel = fromFile. getChannel (); RandomAcc EssFile toFile = new RandomAccessFile (testNIO1.out, rw); FileChannel outChannel = toFile. getChannel (); long position = 0; long count = inChannel. size (); outChannel. transferFrom (inChannel, position, count); fromFile. close (); toFile. close ();} catch (FileNotFoundException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch block e. print StackTrace () ;}/ *** transfer data from FileChannel to another channel */private void channelTransferTo () {try {RandomAccessFile fromFile = new RandomAccessFile (testNIO2.in, rw); FileChannel inChannel = fromFile. getChannel (); RandomAccessFile toFile = new RandomAccessFile (testNIO2.out, rw); FileChannel outChannel = toFile. getChannel (); long position = 0; long count = inChannel. size (); inChannel. tr AnsferTo (position, count, outChannel); fromFile. close (); toFile. close ();} catch (FileNotFoundException e) {// TODO Auto-generated catch block e. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace () ;}/ *** copy file */private void copyFile () {try {ByteBuffer buf = ByteBuffer. allocate (50); RandomAccessFile fromFile = new RandomAccessFile (testNIO3.in, Rw); FileChannel inChannel = fromFile. getChannel (); RandomAccessFile toFile = new RandomAccessFile (testNIO3.out, rw); FileChannel outChannel = toFile. getChannel (); int byteRead = 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 block e. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch block e. printStackTrace ();}}}

 

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.