Java Review--io (input/output) {Java NIO}

Source: Internet
Author: User

The BufferedReader described in http://my.oschina.net/u/2263278/blog/508770 refers to one of its characteristics----when BufferedReader reads data from the input stream, if no valid data is read , where the program will block execution of the thread (using the Read () method of InputStream to fetch data from the stream, it will block the thread if there is no data in the data source), that is, the input stream described earlier, the output stream is blocked input, output. The traditional input and output streams are handled by byte movement, even though we do not directly handle the byte stream, but the underlying implementation is dependent on bytes processing, the stream-oriented input/output system can only process one byte at a time, so the flow-oriented input/output system is usually inefficient. Starting with JDK1.4, Java provides some new IO, which are placed under the Java.nio package and its sub-packages.

I. Overview of new Java IO

The Java NIO uses a memory-mapped file to process the input/output, and the new IO maps a section of the file or file into memory so that the file can be accessed like memory (which simulates the concept of virtual memory on the operating system), in this way input/output is more than the traditional input /output is much faster.

Channel and buffer are the two core objects in NiO, the channel is the simulation of the traditional input/output system, and all the data in the NIO system need to be transmitted by channels. The biggest difference between Channle and the traditional InputStream and OutputStream is that it provides a map () method that maps the "piece of data" directly into memory using the map () method. If the traditional input/output system-oriented flow processing, the new IO is a fast-facing processing. Buffer can be understood as a container whose essence is an array, and all objects sent to the channel must first love you in buffer, and the data read from the channel must first be placed in buffer.

Second, the use of buffer

1, from the internal structure, buffer is like an array, he can save more than one type of data. Buffer is an abstract class whose subclasses: Bytebuffer, Charbuffer, Intbuffer, Longbuffer, and so on. Instead of providing a constructor, these buffer classes return an object through the Allocat (int capacity) method. Bytebuffer also has a subclass: Mappedbytebuffer, which is used to represent the result of a channel mapping part or all of a disk file to memory, usually Mappredbytebuffer is returned by the channel's map () method.

2.3 Concepts in Buffer:

① capacity Capacity: the capacity of the buffer represents the maximum data capacity of the buffers, that is, how much data can be stored. The capacity of the buffer cannot be negative.

② limit: The first buffer position index that should not be read out or written. The data behind the limit is unreadable and cannot be written.

③ position position: record pointer. When data is read from the channel using buffer, its position is 0, and if 2 data is read from the channel into the buffer, position is 2, pointing to the third position in buffer. (The index of the first position is 0)

④mark: Optional Tag

0<=mark<=position<=limit<=capacity

3, the main role of Bufferde is to load data, and then output data, the beginning of the buffer position for the 0,limit for capacity, the program can be put () method into the buffer to put some data, each put some data, The position of the buffer correspondingly moves backwards some positions. When buffer loads the data, call the Flip () method of buffer, which sets the limit to position and the position to 0, which moves the read and write pointers of buffer to the start position. After buffer calls the Filp () method, buffer prepares for the output data. When the buffer output data is finished, buffer calls the clear () method, the clear () method is not to empty the buffer data, it only sets position to 0, the limit is set to capactiy, so that it is ready to load the data into buffer again.

Two important methods in buffer: Flip () and Clear (), the flip () method prepares the data to be fetched from buffer, and the clear () method prepares the data to be loaded again into buffer. There is also the put () and get () methods for putting data into buffer and extracting data from buffer.

When you use put () and get () to access data in buffer, it is divided into relative and absolute two ways:

①, relative: Starts reading or writing data from the current position of buffer, and then increments the value of position by the number of processing elements.

②, Absolute: reading or writing data directly from the index to the buffer, using absolute access to the data in buffer, does not affect the value of the position.

public static void Main (string[] args) {Charbuffer buff=charbuffer.allocate (8);  System.out.println (buff.capacity () + ":" +buff.limit () + ":" +buff.position ());  Buff.put (' a ');  Buff.put (' a ');  Buff.put (' a ');  System.out.println (Buff.position ());  Buff.flip ();     System.out.println (Buff.limit ()); }

The buffer object created by the allocate () method is normal Buffer,bytebuffer also provides a allocatedirect () method to create a direct buffer. The creation cost of the direct buffer is higher than the normal buffer creation cost, but the read efficiency of the direct buffer is high.

Third, the use of channel

The difference between a channel class and a traditional stream object:

The ① and channel can directly map some or all of the specified files into buffer.

②, the program can not directly access the data in the channel, including reading, writing, the channel can only interact with buffer, it is said that if the data from the channel, you must first use buffer to remove some data from the channel, Then let the program take the data out of the buffer. Writing data to Channle, you need to write to buffer first. Java provides the Channle interface with Datagramchannel, FileChannel, Pipe.sinkchannel, Pepe.sourcechannel, Selectablechannel, Serversoketchannel and so on.

All channel should not be created by the constructor, but instead return the corresponding Channle by the traditional node Inputstream,outputstream Getchannel () method. The most commonly used class 3 method in Channle: Map (), read (), write (), where the map () method maps some or all of the data corresponding to the channel into Bytebuffer, while read () and write () method is used to read data directly from buffer or to write data.

public static void Main (string[] args) {try{file F=new file ("Wang.txt");   FileInputStream filein=new FileInputStream (New File ("Wang.txt"));   FileChannel Inchannel=filein.getchannel ();   FileChannel outchannel=new FileOutputStream (New File ("Test.txt")). Getchannel ();   Mappedbytebuffer Buffer=inchannel.map (FileChannel.MapMode.READ_ONLY, 0, F.length ());   Outchannel.write (buffer);  Buffer.clear ();  }catch (Exception e) {e.printstacktrace (); } }

A Getchannel () method is also included in the Randomaccessfile class

public static void Main (string[] args) {try{file File=new file ("Test.txt");   FileChannel channel=new randomaccessfile (file, "RW"). Getchannel ();   Mappedbytebuffer Buff=channel.map (FileChannel.MapMode.READ_WRITE, 0, File.length ());   Channel.position (File.length ());  Channel.write (Buff);  }catch (Exception e) {e.printstacktrace (); } }

Iv. character sets combined channel

Coding encode: Converting a sequence of plaintext characters into a computer-understood binary sequence is called encoding.

Decoding decode: Converting a binary sequence into a plain text string that can be understood by ordinary people is called decoding.

Java uses the Unicode character set by default, and JDK1.4 provides charset to handle the conversion relationship between a sequence of bytes and a sequence of characters that contains methods for creating decoders and encoders, as well as methods to charset the supported character sets, and the CharSet class is immutable.

The Charsetdecoder and Charsetencoder objects represent CharSet's encoders and decoders, calling Charsetdecoder's Decode () method to convert Bytebuffer byte sequences into Charbuff character sequences. Calling Charsetencoder's Encode () method converts a sequence of charbuffer or string characters to a sequence of bytebuffer bytes.

public static void Main (string[] args) throws Charactercodingexception {Charset cn=charset.forname ("GBK");  Charsetencoder Encoder=cn.newencoder ();  Charsetdecoder Decoder=cn.newdecoder ();  Charbuffer Cbuff=charbuffer.allocate (8);  Cbuff.put (' King ');  Cbuff.put (' ning ');  Cbuff.flip ();  Bytebuffer Bbuff=encoder.encode (Cbuff);  for (int i=0;i<bbuff.capacity (); i++) {System.out.println (Bbuff.get (i)); } System.out.println (Decoder.decode (Bbuff)); }

Five, File lock

File locks in the operating system is a common thing, if multiple running programs need to concurrently modify the same file, the program requires some mechanism for communication, using file locks can effectively prevent multiple processes concurrently modifying the same file, so most of the operating system now provides file lock functionality.

Java provides the Filelock class with the ability to support file locks, and the lock ()/trylock () method provided in FileChannel can obtain a file lock Filelock object, thereby locking the file. The difference between the lock () method and the Trylock () method is that when lock () attempts to lock a file, if the file lock cannot be obtained, the program will block until the Trylock () method tries to lock the file, it will return directly instead of blocking, and if a file lock is obtained, The method returns the file lock, otherwise null is returned.

Although file locks can be used to control concurrent access, it is recommended that you use a database to store program information instead of using files for high concurrent access scenarios.

Liu, Nio.2

Java7 has made significant changes to the original NIO, known as nio.2. Provides comprehensive file IO and file system access support. Provides an IO based on an asynchronous channel.

1. Path, paths, and files core API

Java provides a limited file class, he can not take advantage of the characteristics of a particular filesystem, the performance of the method provided by file is not high, and most of its methods fail only to return failure, do not provide exception information. Nio.2 to compensate for this shortcoming, the path interface is introduced and the Files\paths tool class is provided.

2. Filevisitor traversing files and directories

3, watchservice monitoring file changes

Java Review--io (input/output) {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.