NIO and IO in the java file system, and nioio in the java File System

Source: Internet
Author: User

NIO and IO in the java file system, and nioio in the java File System

Java introduced the java NIO mechanism since jdk1.4:

The notable features of NIO are channel, buffer, selector ), non-blocking calls not provided in traditional I/O mechanisms are added to the NIO mechanism (this is useful for network communication and can effectively use the CPU), but this can only be used for network channels (Socketchannel) for filechannel or blocking calls.

We are dedicated to analyzing the file I/O mechanism in java, regardless of the network socket communication mechanism.

In Java, the traditional File system I/O mechanism is Filesystem and File. in java, Filesystem is an internal class in java and does not provide external display features. The File class contains Filesystem objects, therefore, all File operations, such as rename and create etc, are converted to the internal Filesystem operation in java. The following is the abstract class of Filesystem in java:

Abstract class FileSystem {

/**
* Return the FileSystem object representing this platform's local
* Filesystem.
*/
Public static native FileSystem getFileSystem ();


/* -- Normalization and construction --*/

/**
* Return the local filesystem's name-separator character.
*/
Public abstract char getSeparator ();

/**
* Return the local filesystem's path-separator character.
*/
Public abstract char getPathSeparator ();

......

}

Each operating system has a specific file system. In windows, the getFilesystem () Operation of Filesystem is used to obtain the local file system, win32Filesystem. in linux, unixFilesystem is obtained;

In java, File objects in the traditional I/O mechanism include Filesystem objects to manage files in the File system, such as create, delete, and rename. For file I/O data streams, input and output, Fileinputstream and Fileoutputstream are used. The following uses Fileinputstream as an example. The file operation functions in Fileinputstream include:

Private native void open (String name) throws FileNotFoundException;

/**
* Reads a byte of data from this input stream. This method blocks
* If no input is yet available.
*
* @ Return the next byte of data, or <code>-1 </code> if the end of
* File is reached.
* @ Exception IOException if an I/O error occurs.
*/
Public int read () throws IOException {
Object traceContext = IoTrace. fileReadBegin (path );
Int B = 0;
Try {
B = read0 ();
} Finally {
IoTrace. fileReadEnd (traceContext, B =-1? 0: 1 );
}
Return B;
}

Private native int read0 () throws IOException;

/**
* Reads a subarray as a sequence of bytes.
* @ Param B the data to be written
* @ Param off the start offset in the data
* @ Param len the number of bytes that are written
* @ Exception IOException If an I/O error has occurred.
*/
Private native int readBytes (byte B [], int off, int len) throws IOException;

Public native long skip (long n) throws IOException;

The above are several important functions. Each time a File is read, there is a File Reading location. In a linux File system, it is a File descriptor FileDescriptor, while in a windows system it is a handler, the read location is completed by FileDescriptor or Handler, and the file operation can only be read from the previous location at a time.

However, the NIO (New I/O) in Java introduces FileChannel, which has the following New features:

The corresponding Filechannel is an abstract class:

Public abstract class FileChannel
Extends AbstractInterruptibleChannel
Implements SeekableByteChannel, GatheringByteChannel, ScatteringByteChannel {...}

The new method is as follows:
/**
* Reads a sequence of bytes from this channel into the given buffer,
* Starting at the given file position.
*
* <P> This method works in the same manner as the {@ link
* # Read (ByteBuffer)} method, bytes t that bytes are read starting at
* Given file position rather than at the channel's current position. This
* Method does not modify this channel's position. If the given position
* Is greater than the file's current size then no bytes are read. </p>
Public abstract int read (ByteBuffer dst, long position) throws IOException;
/**
* Writes a sequence of bytes to this channel from the given buffer,
* Starting at the given file position.
*
* <P> This method works in the same manner as the {@ link
* # Write (ByteBuffer)} method, bytes t that bytes are written starting
* The given file position rather than at the channel's current position.
* This method does not modify this channel's position. If the given
* Position is greater than the file's current size then the file will be
* Grown to accommodate the new bytes; the values of any bytes between
* Previous end-of-file and the newly-written bytes are unspecified. </p>
Public abstract int write (ByteBuffer src, long position) throws IOException;
/**
* Acquires a lock on the given region of this channel's file.
Public abstract FileLock lock (long position, long size, boolean shared)
Throws IOException;
/**
* Forces any updates to this channel's file to be written to the storage
* Device that contains it.
Public abstract void force (boolean metaData) throws IOException;
/**
* Transfers bytes from this channel's file to the given writable byte
* Channel.
* <P> This method is potentially much more efficient than a simple loop
* That reads from this channel and writes to the target channel. Tables
* Operating systems can transfer bytes directly from the filesystem cache
* To the target channel without actually copying them. </p>
Public abstract long transferTo (long position, long count,
WritableByteChannel target)
Throws IOException;
The above is the new method of FileChannel.

The member variables of FileInputStream in the traditional I/O mechanism in Java:

Private final FileDescriptor fd;
That is, the traditional java file system uses the file descriptor to remember the file access location.

The NIO mechanism in java also adopts a similar mechanism:

// Used to make native read and write CILS
Private static NativeDispatcher nd;

// Memory allocation size for mapping buffers
Private static long allocationGranularity;

// Cached field for MappedByteBuffer. isAMappedBuffer
Private static Field isAMappedBufferField;

// File descriptor
Private FileDescriptor fd;
The above is a specific Filechannel class, FilechannelImpl part of the member variables.

 


What are the more prominent features of Java's NIO mechanism than IO?

Asynchronous io is supported in network transmission, which is non-blocking io.
File Reading, using channel and buffer, you can directly map a large piece of data to the memory, which is more efficient.
 
In java, can nio replace io?

Nio is asynchronous Io. It is also a type of IO. How can it be replaced? Nio is used in resumable data transfer and socket communication ..
 

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.