Introduction to Java NiO (non-blocking io) and IO

Source: Internet
Author: User

In the I/O system prior to Java1.4, I am providing a stream-oriented I/O system, the system processes data one byte at a time, one input stream produces one byte of data, one output stream consumes one byte of data, the I/O speed towards the stream is very slow, and NIO is introduced in Java 1.4. This is a block-oriented I/O system, and the system handles processing in blocks, each of which generates or consumes a database in one step, which is much faster to process data by block than by Byte.

There are several core objects in NiO that need to be mastered: buffer, channel, selector (Selector).

Buffer buffers

Buffer is actually a container object, more directly, is actually an array, in the NIO library, all the data are processed in buffer. When the data is read, it is read directly into the buffer, and it is written to the buffer when the data is written, and any time the data in the NIO is accessed, it is placed in the buffer. In a stream-oriented I/O system, all data is written directly or read directly to the stream object.

In NiO, all of the buffer types are inherited from the abstract class buffer, the most common is bytebuffer, for the basic type of Java, basically have a specific buffer type corresponding to it, the inheritance between them as shown:

The following is a simple example of using Intbuffer:

[Java]View PlainCopy print?
  1. Import Java.nio.IntBuffer;
  2. Public class Testintbuffer {
  3. public static void Main (string[] args) {
  4. //Allocate new int buffer, parameter is buffer capacity
  5. The current position of the new buffer will be zero, and its bounds (the restricted position) will be its capacity.  It will have a lower-level implementation array with an array offset of zero.
  6. Intbuffer buffer = intbuffer.allocate (8);
  7. For (int i = 0; i < buffer.capacity (); ++i) {
  8. Int J = 2 * (i + 1);
  9. //Writes the given integer to the current position of this buffer, incrementing the current position
  10. Buffer.put (j);
  11. }
  12. //reset this buffer, set the limit to the current position, and then set the current position to 0
  13. Buffer.flip ();
  14. //See if there are elements between the current position and the restricted position
  15. While (Buffer.hasremaining ()) {
  16. //Reads the integer at the current position of this buffer and increments the current position
  17. Int J = Buffer.get ();
  18. System.out.print (j + "");
  19. }
  20. }
  21. }

After running, you can see:

We will continue to analyze the buffer object and several of its important properties later.

Channel channels

A channel is an object through which data can be read and written, and of course all data is handled through the buffer object. We never write bytes directly into the channel, but instead write the data to a buffer that contains one or more bytes. The same does not read the bytes directly from the channel, but instead reads the data from the channel into the buffer and fetches the byte from the buffer.

In NiO, a variety of channel objects are provided, and all channel objects implement the channels interface. The inheritance relationship between them is as follows:

Using NIO to read data

As we said earlier, any time the data is read, it is not read directly from the channel, but is read from the channel to the buffer. So the use of NIO to read data can be divided into the following three steps:
1. Get Channel from FileInputStream
2. Create buffer
3. Reading data from the channel into buffer

Here is a simple example of using NIO to read data from a file:

[Java]View PlainCopyprint?
  1. Import java.io.*;
  2. Import java.nio.*;
  3. Import java.nio.channels.*;
  4. Public class Program {
  5. static public void Main (String args[]) throws Exception {
  6. FileInputStream fin = new FileInputStream ("C:\\Test.txt");
  7. //Get channel
  8. FileChannel FC = Fin.getchannel ();
  9. //Create buffers
  10. Bytebuffer buffer = bytebuffer.allocate (1024);
  11. //Read data to buffer
  12. Fc.read (buffer);
  13. Buffer.flip ();
  14. While (buffer.remaining () >0) {
  15. byte B = buffer.get ();
  16. System.out.print (((char) b));
  17. }
  18. Fin.close ();
  19. }
  20. }

Write Data using NiO

Using NIO to write data is similar to the process of reading data, and the same data is written to a buffer instead of directly to the channel, and can be divided into three steps:
1. Get Channel from FileInputStream
2. Create buffer
3. Writing data from the channel to buffer

Here is a simple example of using NIO to write data to a file:

[Java]View PlainCopyprint?
  1. Import java.io.*;
  2. Import java.nio.*;
  3. Import java.nio.channels.*;
  4. Public class Program {
  5. static private final byte message[] = { 111, 109, 101, + ,
  6. 98, 121, 101, 46};
  7. static public void Main (String args[]) throws Exception {
  8. FileOutputStream fout = new FileOutputStream ( "C:\\Test.txt");
  9. FileChannel FC = Fout.getchannel ();
  10. Bytebuffer buffer = bytebuffer.allocate ( 1024);
  11. For (int i=0; i<message.length; ++i) {
  12. Buffer.put (Message[i]);
  13. }
  14. Buffer.flip ();
  15. Fc.write (buffer);
  16. Fout.close ();
  17. }
  18. }

This article introduces two of the three core concepts in Java NIO, and looks at two simple examples of reading and writing data using NIO, the most important piece of nonblocking I/O in Java NiO is analyzed in the third article, and the next chapter describes the internal buffer implementation.

-------------------------------Channel and IO differences----------------------------------

A channel is an object through which data can be read and written. Comparing NIO with the original I/O, the channel is like a stream, and they are facing the buffer. As mentioned earlier, 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 from the channel into the buffer and get the byte from the buffer. The difference between a channel and a stream is that the channel is bidirectional. The stream is only moved in one Direction (a stream must be a subclass of InputStream or OutputStream), and the channel can be used for reading, writing, or both. Because they are bidirectional, the channel can better reflect the real situation of the underlying operating system than the flow. Especially in UNIX models, the underlying operating system channel is bidirectional.

Introduction to Java NiO (non-blocking io) and IO

Related Article

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.