Getting Started with Java NiO

Source: Internet
Author: User

Introduction to NIO

In the previous period of time in the company to deal with some big data, and its word segmentation, extraction of keywords and so on. Although the task is basically completed (the effect is not particularly good), for Java has not been introduced to me for 2 weeks, and I was drunk. Of course, there are knowledge related to machine learning, I would like to continue to record the process of my task, but also to do a summary.

First of all, there is such a file of up to G level, according to Java ordinary I/O is certainly not possible, partition the file, I do not know what year or months to finish reading. So later on the Internet to find relevant information, only to know that there is such a magical NIO.

InJavaProgramming,I/Ois to read the file in a streaming way, allI/Oare treated as a single byte of movement, through aStreamobject to move one byte at a time. Javain the new input/Output (NIO) Library is inJDK1.4introduced in the. NIOmake up for the originalI/Othe lack of it in the standardJavaThe code provides a high-speed, block-orientedI/O. By defining the blocks that contain the data, and by processing the data in a block form ,NIOYou can use low-level optimizations without using native code, which is the originalI/OWhat the package cannot do.

Flow vs. block comparison

The most important difference between the original I/O Library and NiO is the way data is packaged and transmitted, and the original I/o processes the data in a streaming way, and NiO The data is processed in a block manner.

The stream-oriented I/O system processes data one byte at a time, one input stream produces one byte of data, and one output stream produces one byte of data.

A block-oriented I/O system processes data as a block. Each operation generates or consumes a block of data in one step. Processing data by block is much faster than processing data by byte, even if it is not as simple as stream-oriented I/O .

Channels and buffers

Channels and buffers are the core objects in NIO, and are used in almost every I/O operation.

A channel is a simulation of a stream in the original I/O package. All data to any destination or from anywhere must pass through a Channel object. A Buffer is essentially a container object. All objects sent to a channel must first be stored in the buffer, and similarly, any data read from the channel must first be read into the buffer.

What is a buffer?

Buffer is an object that contains some data that you want to write or just read. Adding a Buffer object to the NIO reflects an important difference between the new library and the original I/O . In stream-oriented I/O , you write data directly or read the data directly into the stream object. In the NIO Library, all data is processed in a buffer. When the data is read, it is read directly into the buffer. When the data is written, it is written to the buffer. Whenever you access data in NIO , you put it in a 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 more than just an array. Buffers provide structured access to data, and can also track the read/write process of the system.

Buffer type

The most commonly used buffer type is bytebuffer. A bytebuffer can perform Get/set operations on its underlying byte array (that is, the acquisition and setting of bytes). Bytebuffer is not the only buffer type in NIO . In fact, there is a buffer type for each of the basic Java types:

Bytebuffer

Charbuffer

Shortbuffer

Intbuffer

Longbuffer

Floatbuffer

DoubleBuffer

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

Let's take a look at a simple example of Floatbuffer :

1 ImportJava.io.FileInputStream;2 Importjava.io.FileNotFoundException;3 ImportJava.io.FileOutputStream;4 ImportJava.nio.ByteBuffer;5 ImportJava.nio.FloatBuffer;6 ImportJava.nio.channels.FileChannel;7 8 //Usefloatbuffer9 Ten  Public classUsefloatbuffer { One      A      Public Static voidMain (string[] args)throwsException { -          -Floatbuffer Fb=floatbuffer.allocate (10); the          for(inti=0; I<fb.capacity (); i++) { -             floatF= (float)((float) i/10* (Math.PI)); - fb.put (f); -         } + Fb.flip (); -          while(Fb.hasremaining ()) { +             floatf=fb.get (); A System.out.println (f); at         } -     } -}

What is a channel?

A Channel is an object through which data can be read and written. Compare the NIO with the original I/O and the channel is like a stream. 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. In short, the approximate process for NIO is: Input file---buffer---------buffer----- ------------------ The approximate process is: input file, flow-and process-processing data-flow-and-output file.

Channel type

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.

Practice: Reading and Writing inNIO

Reading and writing are the basic processes 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 fairly straightforward: Create a buffer, populate it with data, and let the channel use that data to perform the write operation.

Read from File

If I am using the original I/O, then we just need to create a FileInputStream and read from it. In NIO , the situation is slightly different: we first get a channel object from fileinputstream and then use this channel to read the data.

In the NIO system, any time a read operation is performed, you are reading from the channel, but you are not reading directly from the channel. Because all of the data eventually resides in the buffer, you are reading the data in the buffer through the channel.

Therefore, it involves three steps to read a file:

(1) Obtaining Channel from fileinputstream

(2) Create Buffer

(3) Read the data from the Channel to Buffer .

1 fileinputstream fin=new fileinputstream ("Read.txt"); 2 filechannel fc=fin.getchannel (); 3 bytebuffer buffer=bytebuffer.allocate (1024x768); 4 fc.read (buffer);

Write file

Writing a file in NIO is similar to reading from a file. First get a channel from FileOutputStream ; The next step is to create a buffer and put some data in it-here, the data will be taken from an array called data, and the last step is to write to the buffer.

 1  fileoutputstream fout=new  FileOutputStream ("Write.txt"  2  filechannel fc=fout.getchannel ();  3  bytebuffer buffer=bytebuffer.allocate (1024) ; 4   int  i=0; i<data.length;      I++  Buffer.put (Data[i]);  6   7  buffer.flip ();     8  fc.write (buffer); 

Practical Practice

We use a simple program called Copyfile.java as the basis for this exercise, which copies all the contents of a file into another file. Copyfile.java performs three basic operations: first create a buffer, then read the data from the source file into this buffer, and then write the buffer to the target file. This program repeats-read, write, read, write-until the source file ends.

1 //CopyFile2 3 ImportJava.io.*;4 ImportJava.nio.*;5 Importjava.nio.channels.*;6 7  Public classCopyFile {8     9     Static  Public voidMain (String args[])throwsException {TenString infile= "e:\\ Beijing welcome you. txt"; OneString outfile= "E:\\out.txt"; A  -FileInputStream fin=NewFileInputStream (infile); -FileOutputStream fout=NewFileOutputStream (outfile); theFileChannel fcin =Fin.getchannel (); -FileChannel fcout =Fout.getchannel (); -  -Bytebuffer buffer = bytebuffer.allocate (1024); +  -          while(true) { + buffer.clear (); A             intR=fcin.read (buffer); at             if(r = =-1) { -                  Break; -             } - Buffer.flip (); - fcout.write (buffer); -         } in     } -}

Getting Started with 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.