Java NIO channel FileChannel [reprint]

Source: Internet
Author: User

Java NIO channel FileChannel [reprint]

@author Zachary.guo

The most powerful thing about file I/O is the asynchronous I/O (asynchronous I/O), which allows a process to request one or more I/O operations from the operating system without waiting for these operations to complete. The process that initiates the request receives a notification that the I/O operation it requested has completed. asynchronous I/O is an advanced performance that many of the current operating systems do not yet have. as a result, file channels are always blocked in most cases and therefore cannot be placed in non-blocking mode.

FileChannel objects cannot be created directly. An FileChannel instance can only be obtained by invoking the Getchannel () method on an open File object (Randomaccessfile, FileInputStream, or FileOutputStream). Calling the Getchannel () method returns a FileChannel object connected to the same file and the FileChannel object has the same access as the file object, and you can use the channel object to take advantage of the powerful FileChannel API has:

Java code
  1. Package java.nio.channels;
  2. Public abstract class FileChannel extends Abstractchannel implements Bytechannel, Gatheringbytechannel , Scatteringbytechannel {
  3. //This is a partial API listing
  4. //All methods listed here can throw java.io.IOException
  5. public Abstract int Read (Bytebuffer DST, long position);
  6. public Abstract int write (bytebuffer src, long position);
  7. public Abstract long size ();
  8. //Returns the position value of the current file.  The return value is a long integer that represents the current byte position in the file.
  9. public abstract long position ();
  10. //sets the position of the channel to the specified value.  Negative value, the exception is served, and values can exceed the end of the file, which results in a hole in the file.
  11. public abstract void position (long newposition);
  12. public abstract void truncate (long size);
  13. public abstract void Force (boolean metaData);
  14. public Final Filelock lock ();
  15. Public Abstract Filelock Lock (long position, long size, Boolean shared);
  16. public final Filelock Trylock ();
  17. public abstract Filelock Trylock (long position, long size, Boolean shared);
  18. Public Abstract Mappedbytebuffer map (mapmode mode, long position, long size);
  19. public Abstract long transferTo (long position, Long Count, Writablebytechannel target);
  20. public Abstract long transferfrom (readablebytechannel src, long position, long Count);
  21. public static class Mapmode {
  22. public static final Mapmode read_only;
  23. public static final Mapmode read_write;
  24. public static final Mapmode PRIVATE;
  25. }
  26. }


As with most channels, FileChannel will attempt to use the local I/O service whenever possible. The FileChannel class itself is abstract, and the actual object you get from the Getchannel () method is an instance (instance) of a specific subclass (subclass), which may use native code to implement some or all of the above API methods.

the FileChannel object is thread-safe (thread-safe). Multiple processes can invoke methods concurrently on the same instance without causing any problems, but not all operations are multithreaded (multithreaded).actions that affect the channel location or affect the file size are single-threaded (single-threaded). If one thread is already performing an operation that affects the channel location or file size, other threads that try to do one of these operations must wait. Concurrency behavior can also be affected by the underlying operating system or file system.

◇ access to files
Each FileChannel object has a one-to descriptor relationship with the same file descriptor, so the API methods listed above are common file I/O on operating systems that are compatible with your favorite POSIX (Portable OS interface) It is not surprising that the system calls are closely aligned.

Essentially, the Randomaccessfile class provides the same abstract content. Before the channel appears, the underlying file operations are implemented by means of the Randomaccessfile class. FileChannel simulates the same I/O service, so its API is naturally very similar.


File I/o API comparison

As with the underlying file descriptor, each filechannel has a concept called "file position". This position value determines which data in the file will be read or written in the next section. Therefore, the FileChannel position (position) is obtained from the underlying file descriptor, which is also shared by the file object that is obtained from the source as a channel reference. And that meansan object's update to the position can be seen by another object:

Java code
  1. Randomaccessfile randomaccessfile = new Randomaccessfile ("filename", "R");
  2. Set the file position
  3. Randomaccessfile.seek (1000);
  4. Create a channel from the file
  5. FileChannel FileChannel = Randomaccessfile.getchannel ();
  6. This would print "1000"
  7. System.out.println ("file pos:" + filechannel.position ());
  8. Change the position using the Randomaccessfile object
  9. Randomaccessfile.seek (500);
  10. This would print "500"
  11. System.out.println ("file pos:" + filechannel.position ());
  12. Change the position using the FileChannel object
  13. Filechannel.position (200);
  14. This would print "200"
  15. System.out.println ("file pos:" + randomaccessfile.getfilepointer ());


An absolute read () operation is attempted at a position outside the end of the file, and the size () method returns a End-of-file. Making an absolute write () on a position that exceeds the file size causes the file to increase to accommodate the new bytes being written.The value of the bytes in the file in the zone between the previous End-of-file position and the newly added byte start location is not specified by the FileChannel class, but in most cases reflects the semantics of the underlying file system. However, in most cases, these voids will be filled with 0.

When you need to reduce the size of a file, the truncate () method cuts all data except for the new size value you specify. If the current size is greater than the new size, all bytes exceeding the new size will be silently discarded. If the new size value provided is greater than or equal to the current file size value, the file is not modified. In both cases, truncate () will have a side effect: The position of the file is set to the new size value provided.

The last API listed above is Force (). This method tells the channel to force all pending modifications to be applied to the file on the disk. All modern file systems cache data and delay disk file updates to improve performance. Calling the Force () method requires that all pending modifications to the file be synchronized to disk immediately.

◇ File Hole
The file offset can be greater than the current length of the file, in which case the next write to the file will extend the file and form an empty hole in the file, which is allowed. Bytes located in the file but not written are set to 0.

If offset is larger than the current length of the file, the next write operation will "extend" the file. This is called creating a "void (hole)" in a file. All bytes that are not actually written to the file are represented by a duplicate of 0.whether the hole occupies hard disk space is determined by the file system.

FileChannel of the Java NIO Channel [reprint]

Related Article

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.