The implementation class of FileChannel in Java NIO is that Filechannelimpl,filechannel itself is an abstract class.
First introduce FileChannel
File Channels is thread-safe. The Close method of the channel can be executed at any time (as required by the channel interface). Any attempt to modify the FileChannel corresponding file size or modify the FileChannel position must be executed serially, and the second operation will block until the previous one runs out. But these methods, in particular, depends on how they are implemented. (Analysis Filechannelimpl below).
You can create FileChannel instances by executing filechannel methods, such as the Open method, or by Java.io.FileInputStream, Java.io.FileOutputStream, Java.io.RandomAccessFile's Getchannel (). (PS: Online said randomaccessfile to get the file lock by default, but I do not find in the official website API and Randomaccessfile.java the relevant instructions and code, some people know how to look at the words, I am skeptical of online views. If you use the FileChannel obtained by Getchannel, FileChannel is associated with objects such as FileInputStream or FileOutputStream (which is why this is analyzed later). That is, for example, to create a new FileInputStream object, and then get a filechannel, when position is 0, then FileInputStream reads 100 bytes, after reading, FileInputStream will definitely read from the 101th byte next time, which is obvious, but the position of the channel you just acquired will also move 100. There is code for proof:
FileInputStream InputStream = new FileInputStream (sourcefile);
byte[] buffer = new BYTE[100];
Bytebuffer BB = bytebuffer.allocate (1024);
FileChannel channel = Inputstream.getchannel ();
SYSTEM.OUT.PRINTLN ("channel" +channel.position ());
int read=inputstream.read (buffer);
SYSTEM.OUT.PRINTLN ("channel" +channel.position () + "read" +read);
Output Result:
Channel 0
Channel Read 100
Go on. FileChannel open mode has read, write, and read and write. FileInputStream gets the nature to be read. OutputStream nature is to write, randomaccessfile to see your randomaccessfile is what mode.
The Append mode (Append-mode) of the FileChannel is determined by the fileoutputstream used. Append mode jumps to the end of the file before starting to write, the atomicity of this operation is supported by the operating system (Filechannel.java in the original Whether the advancement of the position and the writing of the DAT A is-done in a-atomic operation is system-dependent and therefore unspecified).
Java NIO FileChannel Learning Note filechannel Introduction