[Java nio] Channels, Buffers, and niobuffers

Source: Internet
Author: User

[Java nio] Channels, Buffers, and niobuffers

Channels and Buffers are two important concepts in java nio. NIO performs Data Operations Based on Channels and Buffers, and data is always read from Channels to Buffers, or written from Buffers to Channels.

Channel)
  • You can write or read data from the channel;
  • The channel data interacts with the Buffer. The data can be read to the Buffer or written from the Buffer to the channel;
  • Data can also be read and written asynchronously;

Taking FileChannel as an example:

FileChannel

FileChannel is a channel for writing/reading files;

FileChannel generation method:

  • Obtained from FileOutputStream;
  • Obtained from RandomAccessFile;
  • Obtained from FileInputStream;

The following example shows how to obtain the file channel from FileOutputStream, RandomAccessFile, and FileInputStream for related write/read operations;

Package com. pickers. io; import java. nio. *; import java. nio. channels. *; import java. io. *; public class GetChannel {private static final int BSIZE = 1024; public static void main (String [] args) throws Exception {// create a file output byte stream FileOutputStream fos = new FileOutputStream ("data.txt"); // obtain the file channel fc = fos. getChannel (); // write ByteBuffer fc to the channel. write (ByteBuffer. wrap ("Some text ". getBytes (); // close the stream fos. close (); // Random Access File RandomAccessFile raf = new RandomAccessFile ("data.txt", "rw"); // obtain the file channel fc = raf. getChannel (); // set the File Location of the channel to fc at the end. position (fc. size (); // write ByteBuffer fc to the channel. write (ByteBuffer. wrap ("Some more ". getBytes (); // disable raf. close (); // create the file input stream FileInputStream fs = new FileInputStream ("data.txt"); // obtain the file channel fc = fs. getChannel (); // allocate ByteBuffer space size ByteBuffer buff = ByteBuffer. allocate (BSIZE); // read ByteBuffer fc from the channel. read (buff); // call this method to prepare the buff for a series of channel write or relative get operations. flip (); // read bytes from ByteBuffer in sequence and print while (buff. hasRemaining () {System. out. print (char) buff. get ();} fs. close ();}}

There are two ways to copy a file:

  • Open one FileChannel for reading and the other for writing;
  • Directly call the transferTo or transferFrom method to transmit data between channels;

Example code:

Package com. pickers. io; import java. nio. *; import java. nio. channels. *; import java. io. *; public class ChannelCopy {private static final int BSIZE = 1024; public static void main (String [] args) throws Exception {// get the file input/output byte stream FileInputStream FD = new FileInputStream ("C: \ test.jpg"); FileOutputStream fos = new FileOutputStream ("C: \ test_copy.jpg "); // obtain the channel FileChannel fci = fiis from the input/output byte stream of the file. getChannel (); FileChannel fco = fos. getChannel (); // allocate ByteBuffer space size ByteBuffer = ByteBuffer. allocate (BSIZE); // the first data copying method, which writes data directly to the input channel while (fci. read (buffer )! =-1) {// prepare the buffer for the write operation. flip (); // write buffer fco to the output channel. write (buffer); // clears the buffer and resets the internal pointer buffer. clear ();} // The second data copy method. Use the transferTo or transferFrom method FileOutputStream fos2 = new FileOutputStream ("C: \ test_copy2.jpg"); FileChannel fco2 = fos. getChannel (); fci. transferTo (0, fci. size (), fco2); FCM. close (); fos. close (); fos2.close ();}}
Buffer)

Buffer is used to interact with the channel. For example, ByteBuffer is used as an example;

Package com. pickers. io; import java. nio. *; import java. nio. channels. *; import java. io. *; public class GetChannel {private static final int BSIZE = 1024; public static void main (String [] args) throws Exception {// Random Access File RandomAccessFile raf = new RandomAccessFile ("C: \ data.txt", "rw"); // obtain the file channel FileChannel fc = raf. getChannel (); ByteBuffer bf = ByteBuffer. allocate (BSIZE); int bytesRead = fc. read (bf ); // Read into buffer. while (bytesRead! =-1) {// use the flip () method to switch the Buffer from the write mode to the Read mode bf. flip (); while (bf. hasRemaining () {// read one byte at a time. out. print (char) bf. get ();} // clears the cache and prepares to write data to the cache bf. clear (); bytesRead = fc. read (bf);} // disable raf. close ();}}
Basic Buffer method
  • Flip method: called before reading data from the buffer, switched from write mode to read mode;
  • Clear: called before writing data to the buffer, all cleared;
  • compact: Called before writing data to the buffer. Only read data is cleared. newly written data is added to the end of unread data;
Buffer basic attributes
  • Capacity: buffer space size;
  • Position: the pointer used to read and write data. It points to the current position;
  • Limit: indicates the size of the currently readable data when reading data. When writing data, it means the buffer size = capacity;
Buffer type
  • ByteBuffer
  • MappedByteBuffer
  • CharBuffer
  • DoubleBuffer
  • FloatBuffer
  • IntBuffer
  • LongBuffer
  • Protocol Buffer
Write Data in Buffer
  • Writes data from the Channel to the Buffer and calls the Channel's read(Buffer Buffer) Method
  • Write the put () method to the Buffer., CallPut method of Buffer
Read data in Buffer
  • Read data from the Buffer to the Channel, call the Channelwrite(Buffer Buffer) Method
  • Use the get () method to read data from the Buffer,CallBuffer get Method

 

Reference: http://ifeve.com/java-nio-all/

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.