Java NIO FileChannel

Source: Internet
Author: User

http://www.cnblogs.com/puyangsky/p/5840873.html2.2.2 File Channel 2.2.2.1 Open

FileChannel can only be instantiated by a factory method, which is called the Getchannel () method of Randomaccessfile, FileInputStream, and FileOutputStream. Such as:

RandomAccessFile file = new RandomAccessFile("a.txt", "r");FileChannel fc = file.getChannel();
2.2.2.2 use

First look at the method handle provided by FileChannel:

public abstract int read(ByteBuffer dst) throws IOException;//把通道中数据传到目的缓冲区中,dst是destination的缩写public abstract int write(ByteBuffer src) throws IOException;//把源缓冲区中的内容写到指定的通道中去

The clause handle can be seen that FileChannel is both readable and writable, and is full-duplex. Here's an example to show how FileChannel is read and written.

PublicClassfilechanneltest {PublicStaticvoidReadFile (String path) throws IOException {FileChannel FC =New FileInputStream (Path). Getchannel (); Bytebuffer buffer = Bytebuffer.allocate (128); StringBuilder SB =New StringBuilder ();while ((Fc.read (buffer)) >=0) {Flip Pointer Buffer.flip ();Remaining = Limit-positionbyte[] bytes =NewByte[buffer.remaining ()]; Buffer.Get (bytes); StringString =New String (Bytes,"UTF-8"); Sb.append (string);Empty buffer buffer.clear (); } System.Out.println (Sb.tostring ()); }PublicStaticvoidWriteFile (String path, StringString) throws IOException {FileChannel FC =New FileOutputStream (Path). Getchannel (); Bytebuffer buffer = Bytebuffer.allocate (10);int current =0;int len =String.getbytes (). length;while (current < Len) {for (int i=0;i<10;i++) {if (current+i> =len) break; Buffer.put (string.getbytes () [Current+i]);} Current + = Buffer.position (); Buffer.flip (); Fc.write (buffer); Buffer.clear (); }} public static void main (string[] args) throws IOException { String in =  "D:/in.txt"; String out =  "D:/out.txt"; ReadFile ( in); WriteFile (out,  "Hello World"); ReadFile ( out); }} 

Analyze the above code, in the ReadFile () function, get the FileChannel object by Fileinputstream.getchannel (), and create the Bytebuffer object, Then we fill buffer with the Read method of FileChannel, and after we get the filled buffer we flip the current pointer of buffer and then use the Get method of buffer to put the data into a byte array, then we can read the data.

The whole process of reading a file is still a little cumbersome compared to the native I/O method, but if we look at the data as a pile of coal, the bytebuffer as a coal-loaded minecart, and FileChannel as a coal-transporting mine, then the process evolves: get through a mine first, Then put the coal in the car to ship out. Image memory is more conducive to understanding the process.

and the WriteFile () function is similar, in order to better understand the properties of the buffer, I deliberately set the size of buffer to 10, the length of the string to be written is 11 bytes. First, the Fileoutputstream.getchannel () method is used to get the FileChannel object, create a 10-byte buffer, and then define an integer variable current to point to the currently subscript of the string to be written, Each time a byte is put10 to buffer and the current is updated, the position of the pointer after buffer is filled, that is, the number of bytes in the buffer, and the pointer is flipped by the Buffer.position () method. The buffer is finally written to the file by using the Filechannel.write (buffer) method.

Also consider the process of visualization: We first load the coal mine into a trolley (buffer.put ()) and open a mine road (Fileoutputstream.getchannel ()), then transport it into the mine (filechannel.write (buffer)). It's still easy to understand!

Java NIO FileChannel

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.