Java FileChannel usage.
Package com. test. nio; import java. io. fileNotFoundException; import java. io. randomAccessFile; import java. nio. byteBuffer; import java. nio. channels. fileChannel; public class TestFile {/*** @ param args * @ throws FileNotFoundException */public static void main (String [] args) throws Exception {RandomAccessFile aFile = new RandomAccessFile ("H:/test.txt", "rw"); FileChannel inChannel = aFile. getChannel ();/* allocate buffer */ByteBuffer buf = ByteBuffer. allocate (2);/* read to buffer */int bytesRead = inChannel. read (buf); while (bytesRead! =-1) {/* set read */buf. flip ();/* start to read */while (buf. hasRemaining () {System. out. print (char) buf. get ();} buf. clear (); bytesRead = inChannel. read (buf);} aFile. close ();}}
We can understand FileChannel as a file stream. Then we use ByteBuffer to bind it to this file stream, and finally read all the file streams.
Output result
ByteBuffer buf = ByteBuffer. allocate (2); a buffer is allocated in two bytes.
Int bytesRead = inChannel. read (buf); this statement reads a buf from the file stream and returns the read size. If it is read to the end of the file,-1 is returned.
/* Set read */
Buf. flip ();
/* Start reading */
While (buf. hasRemaining ())
{
System. out. print (char) buf. get ());
}
Buf. clear ();
In this section, set buf To Read mode, output the content in buf cyclically, and clear the entire buf.
BytesRead = inChannel. read (buf); this statement continues to read the buf size of the file stream.