Channels and buffers are two of the most important concepts in Java NIO, andNIO is based on Channels and buffers for data manipulation, and data is always read from Channels to Buffers, or write from buffers to Channels.
Channels (channel)
- Can write input from the channel, also can read the data;
- The data of the channel is interacting with buffer, the data can be read to buffer, and the data can be written to the channel from buffer;
- can also read and write data asynchronously;
Take FileChannel, for example, as follows:
FileChannel
FileChannel is the file write/read related channel;
The way to produce filechannel:
- obtained from the FileOutputStream;
- obtained from the Randomaccessfile;
- obtained from the FileInputStream;
Here is an example, respectively, from the FileOutputStream, Randomaccessfile, FileInputStream to obtain the file channel, the relevant write/read operations;
PackageCom.pichen.io;ImportJava.nio.*;Importjava.nio.channels.*;ImportJava.io.*; Public classGetchannel {Private Static Final intBsize = 1024; Public Static voidMain (string[] args)throwsException {//Create a file output byte streamFileOutputStream fos =NewFileOutputStream ("Data.txt"); //Get file ChannelFileChannel FC =Fos.getchannel (); //write bytebuffer to channelFc.write (Bytebuffer.wrap ("Some text". GetBytes ())); //Close the streamFos.close (); //random access to filesRandomaccessfile RAF =NewRandomaccessfile ("Data.txt", "RW"); //Get file ChannelFC =Raf.getchannel (); //set the channel's file location to the endfc.position (Fc.size ()); //write bytebuffer to channelFc.write (Bytebuffer.wrap ("Some More". GetBytes ())); //CloseRaf.close (); //Create a file input streamFileInputStream fs =NewFileInputStream ("Data.txt"); //Get file ChannelFC =Fs.getchannel (); //Allocate bytebuffer space sizeBytebuffer buff =bytebuffer.allocate (bsize); //read Bytebuffer from the channelfc.read (Buff); //call this method to prepare for a series of channel writes or relative fetch operationsBuff.flip (); //reads bytes from the Bytebuffer and prints them sequentially while(Buff.hasremaining ()) {System.out.print (Char) Buff.get ()); } fs.close (); }}
To give an example of a file copy, there are two ways:
- Open a filechannel for reading and another for writing;
- Direct call to Transferto or Transferfrom method to transfer data between channels;
The following code example:
PackageCom.pichen.io;ImportJava.nio.*;Importjava.nio.channels.*;ImportJava.io.*; Public classchannelcopy {Private Static Final intBsize = 1024; Public Static voidMain (string[] args)throwsException {//get file Input output byte streamFileInputStream FIS =NewFileInputStream ("C:\\test.jpg"); FileOutputStream Fos=NewFileOutputStream ("C:\\test_copy.jpg"); //get channel from file input output byte streamFileChannel FCI =Fis.getchannel (); FileChannel FCO=Fos.getchannel (); //Allocate bytebuffer space sizeBytebuffer buffer =bytebuffer.allocate (bsize); //The first Data copy method, directly to the input channel to write data while(Fci.read (buffer)! =-1) { //preparing for a write operationBuffer.flip (); //write buffer to output channelfco.write (buffer); //empty buffer, reset internal pointerbuffer.clear (); } //the second way of copying data, using Transferto or TransferfromFileOutputStream Fos2 =NewFileOutputStream ("C:\\test_copy2.jpg"); FileChannel Fco2=Fos.getchannel (); Fci.transferto (0, Fci.size (), FCO2); Fis.close (); Fos.close (); Fos2.close (); }}Buffers (buffer)
Buffer is used to interact with the channel, for example, here is the example of Bytebuffer;
PackageCom.pichen.io;Import java.nio.*;Import java.nio.channels.*;Import java.io.*;PublicClassGetchannel {PrivateStaticFinalint bsize = 1024;PublicStaticvoid Main (string[] args)ThrowsException {//Random Access file Randomaccessfile RAF =New Randomaccessfile ("C:\\data.txt", "RW");//Get file Channel FileChannel FC =Raf.getchannel (); Bytebuffer BF =Bytebuffer.allocate (bsize);int bytesread = Fc.read (BF);// read into buffer. while (bytesread! = -1// switch buffer from write mode to read mode via the Flip () method Bf.flip (); while (Bf.hasremaining ()) { // read one byte at a time System.out.print (( char// empty cache, ready to write data to cache Fc.read (BF);} // close Raf.close ();} Buffer Basic Method
- Flip method: Call from buffer before reading data, switch from write mode to read mode;
- Clear: Call before buffer to write data, all clear;
compact: Called before the data is written to buffer, only the data that has been read is erased, and the newly written data is added to the end of the unread data;
Buffer Basic Properties
- Capacity:buffer space size;
- Position: Pointer to read and write data, pointing to the current position;
- Limit: The size of the current readable data when reading data, or buffer size =capacity when writing data;
type of buffer
- Bytebuffer
- Mappedbytebuffer
- Charbuffer
- DoubleBuffer
- Floatbuffer
- Intbuffer
- Longbuffer
- Shortbuffer
write data in buffer
- Write from channel to buffer, call the Read
(Buffer buffer)方法
- The put () method writes to buffer.
,调用Buffer的put方法
reading data in buffer
- Read data from buffer to channel, call the
write(Buffer buffer)方法
- Use the Get () method to read data from buffer,
调用Buffer的get方法
Reference: http://ifeve.com/java-nio-all/
JAVA NIO channels and buffers