Input and output of--java NiO

Source: Internet
Author: User

    • The NIO in Java
in the actual development of NIO used not much, I do not mean that NIO use is not much, is to say that I am not a lot of contact, before I reprinted in the blog Park and Csdn 2 others wrote articles, here to roughly summarize the Java NiO, probably understand.
    • Comparison of NiO and traditional IO:
When using the traditional IO, whether the use of the underlying stream of node flow or the use of high-level flow processing flow, the underlying operations are bytes, so performance is not very good, when using BufferedReader this high-level stream will also block the thread, so Java1.4 appeared after NiO.

NIO related classes are placed under the Java.nio package, his function is more powerful. NIO uses different ways (memory-mapped files) to process inputs and outputs, which means that NiO maps a section of a file or file into memory, which can access the file as if it were in memory.


2 cores of NIO: Channel (Channels) and buffer (cache).
    • Describe the following 2 cores:

Buffer is an array. His role is to load data and output data. Buffer has 2 important methods: Flip (remove data from buffer) and clear (Put data into buffer)


The channel can directly map part or all of the specified file directly into buffer. The program also cannot interact with the channel directly, including reading and writing, through buffer, the middle of the thing can be.

    • From theory to Practice: reading and Writing in NIO
Reading and writing are the basic processes of I/O.
1, reading from one channel is simple: just create a buffer and let the channel read the data into this buffer.
2, writing is fairly straightforward: Create a buffer, populate it with data, and let the channel use that data to perform write operations.


    • 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 FileInputStream object from FileInputStream and then use this channel to read the data.
In the NIO system, any time a read operation is performed, it is read from the channel, but it cannot be read directly from the channel. Because all of the data eventually resides in the buffer, it is read from the channel to the buffer.
So it involves three steps to read the file: (1) get the channel from FileInputStream, (2) Create buffer, (3) Read the data from the channel to buffer.
First step: Get the Channel from FileInputStream:
FileInputStream fin = new FileInputStream ("LinkinPark.txt");
FileChannel FC = Fin.getchannel ();
Step Two: Create buffers:
Bytebuffer buffer = bytebuffer.allocate (1024);
Step three: Read the data from the channel into the buffer:
Fc.read (buffer);
Note: We do not need to tell the channel how much data to read into the buffer. Each buffer has a complex internal statistical mechanism that tracks how much data has been read and how much space is available to hold more data.


    • Write file
Writing a file in NIO is similar to reading from a file.
First step: Get a channel from FileOutputStream:
FileOutputStream fout = new FileOutputStream ("LinkinPark.txt");
FileChannel FC = Fout.getchannel ();
Step Two: Create a buffer and put some data in it
Bytebuffer buffer = bytebuffer.allocate (1024);
for (int i=0; i<message.length; ++i) {
Buffer.put (Message[i]);
}
Buffer.flip ();
Step three: Write in buffer
Fc.write (buffer);
Note: It is also not necessary to tell the channel to write multiple data here. The internal statistical mechanism of the buffer tracks how much data it contains and how much data is still to be written.


    • Read-write combination
Let's take a look at what happens when you combine reading and writing. 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.
The CopyFile program lets you see how we check the state of the operation and how to use the clear () and Flip () methods to reset the buffer and prepare the buffer to write the newly read data to another channel. Here is an example:
1, because the buffer tracks its own data, the internal loop of the CopyFile program (inner Loop) is very simple
Fcin.read (buffer);
Fcout.write (buffer);
The first line reads the data from the input channel fcin into the buffer, and the second row writes the data to the output channel fcout.
2, check the status, check when the copy is complete. When there is no more data, the copy is completed and can be returned in the Read () method-1 is to judge this
int r = fcin.read (buffer);
if (r==-1) {
Break
}
3, Reset buffer
Finally, we call the clear () method before reading the buffer from the input channel. Again, before we write the buffer to the output channel, we call the Flip () method
Buffer.clear ();
int r = fcin.read (buffer);
if (r==-1) {
Break
}
Buffer.flip ();
Fcout.write (buffer);
The clear () method resets the buffer so that it can accept the read-in data. The flip () method allows the buffer to write the newly read-in data to another channel.


The following code is roughly used to illustrate the next Java NIO, which I have never used, so it comes directly from the data sticky code:

import java.nio.*;p ublic class buffertest{public static void Main (string[] args) {//    Create Buffercharbuffer buff = charbuffer.allocate (8); ①SYSTEM.OUT.PRINTLN ("Capacity:" + buff.capacity ()); System.out.println ("Limit:" + buff.limit ());      System.out.println ("Position:" + buff.position ());//add Element Buff.put (' a '); Buff.put (' B '); Buff.put (' C ');  ②system.out.println ("After adding three elements, Position =" + buff.position ());//Call The Flip () method Buff.flip (); ③system.out.println ("Execute flip (), limit =" + buff.limit ());  System.out.println ("position =" + buff.position ());//Remove the first element System.out.println ("first element (position=0):" + buff.get ());     ④system.out.println ("After removing an element, Position =" + buff.position ());//Call the Clear Method Buff.clear (); ⑤system.out.println ("Execute Clear (), limit =" + buff.limit ()); System.out.println ("Execute clear (), Position =" + buff.position ());    System.out.println ("Execute clear (), the buffer content is not cleared:" + "The third element is:" + buff.get (2)); ⑥system.out.println ("After performing an absolute read, Position =" + buff.position ());}} 


Import java.io.*;import java.nio.*;import java.nio.channels.*;import java.nio.charset.*;p ublic class FileChannelTest {public static void main (string[] args) {file F = new File ("Filechanneltest.java"); try (//Create FileInputStream, Create Filechannelfilechannel Inchannel = new FileInputStream (f) with the file input stream. Getchannel ();//create Filebuffer with file output stream, To control the output filechannel Outchannel = new FileOutputStream ("A.txt"). Getchannel ()) {// Map all data in FileChannel to bytebuffermappedbytebuffer buffer = Inchannel.map (FileChannel.MapMode.READ_ONLY, 0, F.length ()   );     ①//uses the GBK character set to create the decoder charset charset = Charset.forname ("GBK"), and//directly outputs the data in buffer outchannel.write (buffer); ②//calls the clear () method of buffer again, restoring the position of limit, position buffer.clear ();//Create Decoder (Charsetdecoder) object Charsetdecoder decoder = Charset.newdecoder ();//Use decoder to convert Bytebuffer to Charbuffercharbuffer charbuffer = decoder.decode (buffer);// The ToString method of Charbuffer can get the corresponding string System.out.println (Charbuffer);} catch (IOException ex) {ex.printstacktrace ();}}}

Import java.io.*;import java.nio.*;import java.nio.channels.*;p ublic class randomfilechanneltest{public static void Main (string[] args) throws ioexception{file f = new File ("A.txt"), try (//Create a Randomaccessfile object Randomaccessfile RAF = new Randomaccessfile (F, "RW");//Get randomaccessfile corresponding Channelfilechannel Randomchannel = Raf.getchannel ()) {// Map all the data in the channel into bytebufferbytebuffer buffer = Randomchannel.map (FileChannel.MapMode.READ_ONLY, 0, F.length ());// The record pointer of the channel is moved to the last Randomchannel.position (F.length ());//The output of all data in buffer is randomchannel.write (buffer);}}

Import java.io.*;import java.nio.*;import java.nio.channels.*;import java.nio.charset.*;p ublic class ReadFile{public static void Main (string[] args) throws Ioexception{try (//create file input stream FileInputStream fis = new FileInputStream (" Readfile.java ");//Create a Filechannelfilechannel fcin = Fis.getchannel ()) {//define a Bytebuffer object for repeated fetching of water bytebuffer Bbuff = Bytebuffer.allocate (64);//FileChannel data into Bytebuffer while (Fcin.read (bbuff)! =-1) {//Lock buffer blank area bbuff.flip (); /Create CharSet Object CharSet charset = Charset.forname ("GBK");//Create Decoder (Charsetdecoder) object Charsetdecoder decoder = Charset.newdecoder ();//transcoding the contents of bytebuffer charbuffer Cbuff = Decoder.decode (Bbuff); System.out.print (Cbuff);//Initialize buffer to prepare for the next read of the data Bbuff.clear ();}}}


Finally, there are 2 knowledge about the Java NIO, one is encoding and decoding, the other is file lock

Encoding and decoding: We often want the most data to encode and decode when playing the Java EE, because to the front and back table interaction data, here the encoding and decoding is mainly said that we use NIO when the file read and write operations used to encode and decode. Encoding is the conversion of a sequence of strings of plaintext into a sequence of bytes understood by a computer, and decoding is the conversion of a sequence of bytes into a clear-text string that ordinary people can read. For me to use the largest set of 2 strings, one is the GBK (Simplified Chinese character set) one is UTF-8 (8-bit UCS conversion format).

Import Java.nio.charset.*;import java.util.*;p ublic class charsettest{public static void Main (string[] args) {// Get all the character sets supported by Java sortedmap<string,charset>  map = Charset.availablecharsets (); for (String Alias:map.keySet () {//The alias of the output character set and the corresponding CharSet object System.out.println (alias + "----->" + map.get (alias));}}

Import Java.nio.*;import java.nio.charset.*;p ublic class charsettransform{public static void Main (string[] args) throws exception{//create Simplified Chinese corresponding to charsetcharset cn = Charset.forname ("GBK");//Get the encoder and decoder corresponding to the CN object Charsetencoder Cnencoder = Cn.newencoder (); Charsetdecoder Cndecoder = Cn.newdecoder ();//Create a Charbuffer object Charbuffer Cbuff = charbuffer.allocate (8); Cbuff.put (' Sun ' ); Cbuff.put (' Enlightenment '); Cbuff.put (' empty '); Cbuff.flip ();//convert character sequences in Charbuffer to byte sequences bytebuffer Bbuff = Cnencoder.encode (Cbuff) ;//Iterate through each byte in bytebuffer for (int i = 0; i < bbuff.capacity (); i++) {System.out.print (Bbuff.get (i) + "");} Decodes the Bytebuffer data into a character sequence System.out.println ("\ n" + cndecoder.decode (Bbuff));}}


File locks are common on the operating system, and using file locks can effectively prevent multiple processes from modifying the same file concurrently. In fact, the lock is similar to the database.

Import java.io.*;import java.nio.*;import java.nio.channels.*;p ublic class filelocktest{public static void Main (String [] args) throws Exception{try (//Use FileOutputStream to get filechannelfilechannel channel = new FileOutputStream ("A.txt"). Getchannel ()) {//Use a non-blocking method to lock the specified file Filelock lock = Channel.trylock ();//program Pause 10sthread.sleep (10000);//Release lock Lock.release () ;}}}



Input and output of--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.