Packagecom.test;ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.RandomAccessFile;ImportJava.nio.ByteBuffer;ImportJava.nio.channels.FileChannel; Public classGetChannel1 {Private Static intBsize = 1024; Public Static voidMain (string[] args)throwsException {GetChannel1 GetChannel1=NewGetChannel1 (); Getchannel1.writefile ("File.txt", "Hello,"); Getchannel1.addtofile ("File.txt", "World"); Getchannel1.readfile ("File.txt"); } Public voidReadFile (String fileName)throwsIOException {FileChannel FC=NewFileInputStream (fileName). Getchannel (); Bytebuffer Buff=bytebuffer.allocate (bsize); Fc.read (Buff); /*** Flips this buffer. The limit is set to the current position * and then the position are set to zero. * If The mark is defined then it is discarded. After a sequence of channel-read or put operations, invoke the This method to prepare for a sequence of CHANNEL-WR ITE or relative get operations. */Buff.flip (); /** Tells whether there is any elements between the current position and the limit. */ while(Buff.hasremaining ()) {System.out.print (Char) Buff.get ()); } fc.close (); } //add content to a file Public voidAddtofile (string fileName, string content)throwsIOException {FileChannel FC=NewRandomaccessfile (FileName, "RW"). Getchannel (); Fc.position (Fc.size ()); Fc.write (Bytebuffer.wrap (Content.getbytes ())); Fc.close (); } //Write a file Public voidWriteFile (string fileName, string content)throwsFileNotFoundException, IOException {FileChannel FC=NewFileOutputStream (fileName). Getchannel (); Fc.write (Bytebuffer.wrap (Content.getbytes ())); Fc.close (); }}
Java NIO code demonstrates three kinds of streams