Java IO Learning Summary (iv)

Source: Internet
Author: User

First, NIO

NIO uses a memory-mapped file to process the input-output stream, mapping a section of a file or file into memory, so that it can access the file as if it were accessing memory faster than the traditional input-output stream. The main two core objects are channel (channels) and buffer (buffer).

1) Buffer

Buffer is an abstract class, the main implementation class is Bytebuffer, and the other basic data types have corresponding buffer classes. Commonly used bytebuffer and charbuffer;

Creates a buffer object that, through the static Xxbuffer allocate (int capacity) method, capacity represents the capacity.

There are three key concepts in buffer, capacity (capacity), bounds (limit), and position (position)

Capacity: Represents the maximum data capacity of a buffer and cannot be negative, and cannot be changed after creation.

Bounds: A buffer index position that indicates that data cannot be read out or written to.

Position: Represents the next buffer position index that can be read or written, when a buffer object is created, position is 0, and after reading two data from it, position is 2, pointing to the third data position in buffer. Similar to writing, the position automatically moves backwards in position.

Two important methods in buffer: Flip () and clear (); after the flip () method, the limit moves to the position position, the position is set to 0, the output data is ready, and after the clear () method is executed, Limit moves to the capacity position, and the position position is set to 0 to prepare for writing the data.

Buffer common Operation Sample code:

 Public classBuffertest { Public Static voidMain (string[] args) {//Create bufferCharbuffer buff = charbuffer.allocate (10); //when initialized: position position is 0,limit position equals capacitySYSTEM.OUT.PRINTLN ("Buffer Capacity:" +buff.capacity ()); System.out.println ("Initialize position location:" +buff.position ()); System.out.println ("Initialize limit position:" +buff.limit ()); //put three data into the bufferBuff.put (' A '); Buff.put (B); Buff.put (C); //at this point the position position is 3,limit position equal to capacitySYSTEM.OUT.PRINTLN ("Position location when loading data:" +buff.position ()); System.out.println ("Limit position when loading data:" +buff.limit ()); //Loading Data EndBuff.flip (); //view position position at this time is 0,limit position is 3SYSTEM.OUT.PRINTLN ("Load data Complete Position location:" +buff.position ()); System.out.println ("Load data complete limit position:" +buff.limit ()); //when the data is removed, the position automatically moves backwards, using the Buff.get (X) position position, only when the Buff.get () method is used. System.out.println ("Remove First Data" +buff.get ()); System.out.println ("Remove Data Position location:" +buff.position ()); //Remove data to completebuff.clear (); //view position position at this time is 0,limit position equals capacitySYSTEM.OUT.PRINTLN ("Remove data to complete position location:" +buff.position ()); System.out.println ("Remove data to complete limit position:" +buff.limit ()); }}

2) Channel

Channel is similar to the traditional stream object, can directly map the part or all of the specified file into buffer, the program does not directly access the channel, must interact through buffer, all channel can not be directly created by the constructor, Instead, the channel is returned through the traditional method of node InputStream, OutStream, Getchannel ().

The channel has three main methods, map (), read (), and write (), and the map () method is used to map the data in the channel into Bytebuffer.

Sample code

 Public classChanneltest { Public Static voidMain (string[] args) {Try {            //Create a fileFile File =NewFile ("D:\\test.txt"); //create input and output channelFileChannel fic =Newfileinputstream (file). Getchannel (); FileChannel FOC=NewFileOutputStream ("D:\\channel.txt"). Getchannel (); //Map the contents of the file to BytebufferMappedbytebuffer buffer = Fic.map (mapmode.read_only, 0, File.length ()); //outputting data from buffer to FileChannelfoc.write (buffer); //Initializing buffersbuffer.clear (); //creating a decoder for buffer conversionsCharset Charset = Charset.forname ("GBK"); Charsetdecoder CD=Charset.newdecoder (); //convert Bytebuffer to Charbuffer for data output displayCharbuffer Charbuff =cd.decode (buffer); System.out.println (The data is: "+Charbuff); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }    }}

Another way to read

 Public classChannelTest1 { Public Static voidMain (string[] args) {Try{File File=NewFile ("D:\\test.txt"); FileChannel FCI=Newfileinputstream (file). Getchannel (); //Define BufferBytebuffer buff = bytebuffer.allocate (256);  while(Fci.read (buff)! =-1){                //Lock cache area to prevent reading nullBuff.flip (); //Create a decoder to convert to Charbuffer outputCharset Charset = Charset.forname ("GBK"); Charsetdecoder Decode=Charset.newdecoder ();                                System.out.println (Decode.decode (buff)); //after the data has been read, initialize the bufferbuff.clear (); }        } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }    }}

Java IO Learning Summary (iv)

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.