Java Core Learning (18) Javanio Framework---"block" model IO

Source: Internet
Author: User

I. Overview of new Java IO

The input and output streams in the Javaio are handled through byte movement, and the stream-oriented input-output system can handle only one byte at a time, so it is inefficient and the traditional input-output stream is blocked, meaning that when the data is unreadable, the current thread is blocked until it is read to a valid data to continue running.

After java1.4, a series of improved input and output classes and methods are provided, and the classes in the Java.io package are rewritten on the basis of NIO, and the functionality to meet NiO is added.

NIO uses a memory-mapped file, and the main packages in Java.nio are:

Java.nio, mainly contained in the buffer related classes;

Java.nio.charset, which mainly contains character set-related classes;

Java.nio.channels, consisting mainly of channel and selector related classes;

Java.nio.channels.spi, mainly contains the channel related service provider programming interface;

JAVA.NIO.CHARSET.SPI, which contains the service provider programming interfaces associated with the character set.

Second, buffer abstract class

Its subclasses have Bytebuffer (most commonly used), Charbuffer, Shortbuffer, Intbuffer, Longbuffer, Floatbuffer, DoubleBuffer, and these classes do not have constructors. Gets the buffer object used as the following static method: Static Xxxbuffer allocate (int capacity).

Several positional properties of buffer:

  

The corresponding two methods: Clear (), let limit = capacity and position = 0, which is equivalent to preparing the data for writing to buffer again,

Flip (), let limit = position and position = 0, which is equivalent to preparing to extract data from buffer.

 Packageniotest;ImportJava.nio.CharBuffer; Public classBuffertest { Public Static voidMain (string[] args) {Charbuffer buffer= Charbuffer.allocate (8); System.out.println ("Capacity:" +buffer.capacity ()); System.out.println ("Limit:" +buffer.limit ()); System.out.println ("Position" +buffer.position ()); Buffer.put (A); Buffer.put (' B '); Buffer.put (C); System.out.println ("After adding three elements, Position =" +buffer.position ());        Buffer.flip (); System.out.println ("After Flip () is executed, limit =" +buffer.limit ()); System.out.println ("Position =" +buffer.position ()); //Remove the first elementSystem.out.println ("first element (position=0):" +buffer.get ()); System.out.println ("After removing the first element, Position =" +buffer.position ()); //call the Clear methodbuffer.clear (); System.out.println (After executing clear (), limit = "+buffer.limit ()); System.out.println (After the clear () is executed, position = "+buffer.position ()); System.out.println ("When clear () is executed, the buffer content is not cleared:" + "The third element is:" + buffer.get (2)); System.out.println ("After performing an absolute read, Position =" +buffer.position ()); }}

The above code tried the use of buffer, the output for the next

Capacity:8limit:8= 3= 3= 0 First element (position=0= 1= 8  = 0= 0

The above program uses the buffer is Heapbuffer, each heapbuffer creates a corresponding directbuffer in the new, the direct buffer reads the high efficiency but the creation cost is also high, the specific buffer1 work way not in here to delve into =, Because it is not practical application will also forget.

Third, channel interface

Channel is used to interact with buffer to achieve IO of data.

Java provides the channel interface with Datagramchannel (support for UDP network communication), FileChannel (file read/write), Pipe.sinkchannel and Pipe.sourcechannel (pipelines that support inter-thread communication), Selectablechannel (optionally blocking and non-blocking channel), Serversocketchannel and Socketchannel (support for TCP network traffic), and so on.

The channel passes through the traditional flow node to return the corresponding channel, the commonly used methods are map (), read (), write (), try it below

  

 Packageniotest;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.nio.CharBuffer;ImportJava.nio.MappedByteBuffer;ImportJava.nio.channels.FileChannel;ImportJava.nio.charset.Charset;ImportJava.nio.charset.CharsetDecoder; Public classFilechanneltest { Public Static voidMain (string[] args) {File F=NewFile ("./src/main/java/niotest/filechanneltest.java")); Try(FileChannel inchannnel=NewFileInputStream (f). Getchannel (); FileChannel Outchannel=NewFileOutputStream ("A.txt"). Getchannel (); ) {Mappedbytebuffer buffer= Inchannnel.map (FileChannel.MapMode.READ_ONLY, 0, F.length ()); Charset Charset= Charset.forname ("GBK");            Outchannel.write (buffer);            Buffer.clear (); Charsetdecoder Decoder=Charset.newdecoder (); Charbuffer Charbuffer=decoder.decode (buffer);        System.out.println (Charbuffer); } Catch(IOException IoE) {ioe.printstacktrace (); }    }}

Each time the following code runs, a copy of the contents of the A.txt file is copied and all the contents are appended to the file

 Packageniotest;ImportJava.io.File;Importjava.io.IOException;ImportJava.io.RandomAccessFile;ImportJava.nio.ByteBuffer;ImportJava.nio.channels.FileChannel; Public classRandomfilechanneltest { Public Static  voidMian (string[] args) {File F=NewFile ("A.txt"); Try(Randomaccessfile RAF=NewRandomaccessfile (F, "RW"); FileChannel Randomchannel=Raf.getchannel (); ) {Bytebuffer buffer= Randomchannel.map (filechannel.mapmode.read_only,0, F.length ());
The position of the channel is moved here, and the data can be written to the channel at any location. Randomchannel.position (F.length ()); Randomchannel.write (buffer); }Catch(IOException IoE) {ioe.printstacktrace (); } }}

Four, CharSet class

The character set class is mainly used for text Format data encoding and decoding, the use of the first example in three shows.

Java Core Learning (18) Javanio Framework---"block" model 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.