Java NIO principle and its advantages

Source: Internet
Author: User

To be clear about the principles of NIO and its merits, it is clear how the Java application's file read and write principles and the principles of virtual memory are. The Java file reading principle can be seen in the following figure:


When the application needs to read the file, the kernel first reads the contents of the file from disk into the buffer in the kernel through DMA technology, and then the Java application process then reads the data into the buffer of the application from the buffer of the kernel.

In order to improve I/O efficiency and processing power, the operating system adopts the mechanism of virtual memory. Virtual memory is what we often say swap memory, it is actually the file on the hard disk, virtual memory has two functions:

1. Different virtual memory can be mapped to the same physical memory, according to this principle, can simplify the file reading process, improve reading efficiency, the effect shown in the following figure:


Using virtual memory technology, the application's buffer and kernel buffer as virtual memory, and two different virtual memory point to the same physical memory, the kernel through DMA to read the data to buffer, the application can use the data directly.

2. By using virtual memory, applications can use much larger memory than physical memory, and can also improve I/O efficiency. When data in physical memory is not used, the data in physical memory can be put into virtual memory, and the operating system frees up the physical memory space to store the new data to be processed. When you need to use the data in virtual memory, you can then load the data in virtual memory into physical memory. So physical memory can be viewed as a cache of data stored in virtual memory. The process of the cache virtual memory data described above is transparent to the application, which can process data in virtual memory as it does with physical memory data.


Java NiO directly corresponds to the file pages and application space in the file system by using virtual memory technology, and the read and write operations of the files are implemented in virtual memory after the use of NIO. This way, when manipulating a file, it seems as if the file is already in memory. Using the virtual memory technology, the Java NiO method can quickly read large files.

Java NiO opens a file to specify the location of the mapped content in the file you want to map. Open File source code using Java NIO:

Import Java.io.RandomAccessFile;
Import Java.nio.MappedByteBuffer;
Import Java.nio.channels.FileChannel;
 
public class Memorymappedfileexample
{
    static int length = 0X8FFFFFF//128 Mb public
 
    static void main (String [] args throws Exception
    {
        Mappedbytebuffer out = new Randomaccessfile ("Howtodoinjava.dat", "RW")
                                    . Getchannel (). Map (FileChannel.MapMode.READ_WRITE, 0, length);
        for (int i = 0; i < length; i++)
        {
            out.put ((Byte) ' x ');
        }
        System.out.println ("finished writing");
    }



Using Java nio to read file content source code:

Import Java.io.File;
Import Java.io.RandomAccessFile;
Import Java.nio.MappedByteBuffer;
 
Import Java.nio.channels.FileChannel;
 
    public class Memorymappedfilereadexample {private static String Bigexcelfile = "Bigfile.xls"; public static void Main (string[] args) throws Exception {//create file Object file = new file (bi
         
        Gexcelfile);
         
        Get file Channel in readonly mode FileChannel FileChannel = new Randomaccessfile (file, "R"). Getchannel (); Get direct byte buffer access using CHANNEL.MAP () operation Mappedbytebuffer buffer = FILECHANNEL.M
         
        AP (FileChannel.MapMode.READ_ONLY, 0, Filechannel.size ());
        The buffer now reads the ' file as if it were loaded in memory.  System.out.println (buffer.isloaded ());  Prints false System.out.println (buffer.capacity ()); Get the size based on content size of file//you can read the file from this buffer the way for you likE. for (int i = 0; i < buffer.limit (); i++) {System.out.print ((char) buffer.get ());//prin t the content of File}}


To write the new contents of a file using Java NiO:

Import Java.io.File;
Import Java.io.RandomAccessFile;
Import Java.nio.MappedByteBuffer;
Import Java.nio.channels.FileChannel;
 
public class Memorymappedfilewriteexample {
    private static String Bigexcelfile = "test.txt";
 
    public static void Main (string[] args) throws Exception {
        //Create File object
        file = new file (bigexcelfile) ;
         
        Delete the file; We'll create a new file
        file.delete ();
 
        Get file Channel in readonly mode
        filechannel filechannel = new Randomaccessfile (file, rw). Getchannel ();
 
        Get direct byte buffer access using CHANNEL.MAP () operation
        Mappedbytebuffer buffer = Filechannel.map (filechannel . Mapmode.read_write, 0, 4096 * 8 * 8);
 
        Write the content using put methods
        buffer.put ("howtodoinjava.com". GetBytes ());
    }


The advantages of Java NiO are visible:

1. You do not need to use the read () or write () operation to process the contents of the file

2. Modify the file, modify the automatic flush to the file

3. NiO can quickly deal with large documents and processing efficiency quickly


Reference articles:

http://howtodoinjava.com/2014/12/10/how-java-io-works-internally-at-lower-level/

http://howtodoinjava.com/2015/01/16/java-nio-2-0-memory-mapped-files-mappedbytebuffer-tutorial/







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.