[Java]nio (i)--Overview __nio

Source: Internet
Author: User
Tags prepare

Background component channel and buffer read-write instance

background

A new JAVAI/O class library is introduced into the java.nio.* package of JDK1.4, which aims to improve speed. In fact, the old I/O package has been implemented using NIO again. Therefore, even if you do not explicitly use NiO to write code, you can benefit from it.
I/O application scenarios are divided into file I/O and network I/O, where the former is studied. Components

NIO has three main components: Channel (Channel), buffer (buffer), Selector (select area).
NIO is faster because the data transmission structure of NIO is closer to the way the OS performs I/O: the channel and the buffer , while traditional I/O is oriented to byte streams and characters.
  The channel is used for storing data, the buffer is used to transmit data, and the selection area is used to monitor multiple channel events (for example: Connection open, data arrival). Channels and Buffers

We don't interact directly with the channel, we just interact with the buffer and send the buffer to the channel. The channel either obtains data from the buffer or sends data to the buffer. The only buffer that the
interacts directly with the channel is Bytebuffer, which is the buffer that can store the unprocessed bytes. It is a very basic class: Create a Bytebuffer object by telling how much storage is allocated, and there is also a selection set. The is used to output and read data in the original byte form or base data type . However, it cannot directly read or output objects , even if it is a string object. Although this kind of processing is very low-level, but is more fitting the operating system the processing way.
The three classes in the old I/O class library, FileInputStream, FileOutputStream, Randomaccessfile, were modified to produce filechannel. These three classes are byte manipulation flows , consistent with the properties of NiO. Class-oriented character streams like reader and writer cannot be used to generate channels, but java.nio.channels.Channels classes provide a way to generate reader and writer in the channel. reading a realistic example

public class Getchannel {private static final int bsize = 2014;
         public static void Main (string[] args) throws IOException {/** * Write data, * If existing content, the original content will be overwritten;
        * If no file exists, a new file is created and the new content is written./FileChannel FC = new FileOutputStream ("Data.txt"). Getchannel ();
        Fc.write (Bytebuffer.wrap ("some text". GetBytes ()));

        Fc.close ();
        /** * Add content to end of file */fc = new Randomaccessfile ("Data.txt", "RW"). Getchannel ();     Fc.position (Fc.size ());
        Move to the end of the file Fc.write (Bytebuffer.wrap ("Some more". GetBytes ()));


        Fc.close ();
        /** * Read File/fc = new FileInputStream ("Data.txt"). Getchannel ();
        Bytebuffer buff = bytebuffer.allocate (bsize);
        Fc.read (Buff);
        Buff.flip ();
        while (Buff.hasremaining ()) {System.out.print ((char) buff.get ()); }
    }
}
Channel: For the above three kinds of flow classes, the Getchannel () method can obtain a filechannel. A channel is a fairly basic thing: it can be transfer of Bytebuffer for reading and writing, and you can lock certain areas of the file for exclusive access Bytebuffer: One way to store bytes in Bytebuffer is to use a The put method fills them directly, fill in one or more bytes, or the value of the base data type. can also use the Wrap () method to "wrap" an existing byte array into BytebufferSo that an array is packaged as a bytebuffer buffer, and once the wrapper is complete, the underlying data can be accessed through the buffer or directly. We call the second type array supported by theBytebuffer Position: You can use the FileChannel position method to move FileChannel in a file. In the example above it is moved to the end of the file to facilitate the increase in content. Allocate: For read-only access, we want to explicitly use the static allocate () method to allocate the Bytebuffer,nio goal is to quickly move large amounts of data, so the size of the bytebuffer is particularly important--in fact, The 1K used here may be a little bit smaller than we normally use (we have to actually run the program to find the best size). Use Allocatedirect instead of allocate to produce a "direct" buffer with higher coupling to the operating system and possibly a higher speed. However, this allocation increases expenditure and the specific implementation varies depending on the operating system. Read () and Flip (): Once you call Read () to tell FileChannel to Bytebuffer storage bytes, you must call Flip () on the buffer to make it ready for others to read bytes. If you intend to use the buffer to perform further read () operations, we must also call clear () to prepare for each read (). The following example:
public class Channelcopy {

    private static final int bsize = 2014;

    public static void Main (string[] args) throws IOException {
        FileChannel in = new FileInputStream ("src/main/resources/ In.txt "). Getchannel ();
        FileChannel out = new FileOutputStream ("Src/main/resources/out.txt"). Getchannel ();

        Bytebuffer buffer = bytebuffer.allocate (bsize);
        while (in.read (buffer)!=-1) {
            buffer.flip ();  Prepare to write
            out.write (buffer);
            Buffer.clear ();  Ready to read
        }

        /**
          * Commonly used is direct use of transferTo or Transferfrom
//        In.transferto (0, In.size (), Out);         or Out.transferfrom (in, 0, in.size ());
    }

Here are two filechannel, one for reading and one for writing. After each read () operation, the data is entered into the buffer, and flip () prepares the buffer so that its information can be extracted by write (). After the write () operation, the information is still in the buffer, and the clear () action is rescheduled for all internal pointers so that the buffer is ready to receive data during another read () operation.
Operations such as file content replication, generally using Transferto or Transferfrom methods

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.