Java new I/O channels and buffers

Source: Internet
Author: User

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

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.