Java FileChannel usage.

Source: Internet
Author: User

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.


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.