Package Io;import Java.nio.*;import Java.nio.channels.*;import java.io.*;/* * Three types of streams are used to generate writable, readable, readable and writable channels. * Getchannel () will produce a filechannel channel that can transmit bytebuffer for read-write to him, and can lock certain areas of the file for exclusive access. * The method of placing bytes in Bytebuffer is used in the Put method, or the Wrap method is used to wrap the existing byte array into the Bytebuffer. Once this is done, the underlying array is not copied * instead it is used as the memory for the resulting bytebuffer, called the array-supported Bytebuffer. * Once you call read () to tell FileChannel to store bytes to Bytebuffer, you must call Flip () on the buffer to prepare him for reading bytes. */public class Getchannel {private static final int bsize = 1024; @SuppressWarnings ("resource") public static void main (string[] args) throws Exception {//Write a file: @SuppressWar Nings ("resource") FileChannel FC = new FileOutputStream ("Data.txt"). Getchannel (); Fc.write (Bytebuffer.wrap ("Some text". GetBytes ())); Fc.close (); Add to the end of the FILE:FC = new Randomaccessfile ("Data.txt", "RW"). Getchannel (); Fc.position (Fc.size ()); Move to the End Fc.write (Bytebuffer.wrap ("Some more". GetBytes ())); Fc.close (); Read the FILE:FC = new FileInputStream ("Data.txt"). GetchanNel (); Bytebuffer buff = bytebuffer.allocate (bsize); Fc.read (Buff); Buff.flip (); while (Buff.hasremaining ()) System.out.print ((char) buff.get ()); }}/* Output:some text Some more*///:~
Java new I/O channels and buffers