JAVA NIO 緩衝區buffer實例





緩衝區(Buffer)

Java NIO中的Buffer用於和NIO通道進行交互。如你所知,數據是從通道讀入緩衝區,從緩衝區寫入到通道中的。 
緩衝區本質上是一塊可以寫入數據,然後可以從中讀取數據的內存。這塊內存被包裝成NIO Buffer對象,並提供了一組方法,用來方便的訪問該塊內存。 

Buffer的基本用法 
使用Buffer讀寫數據一般遵循以下四個步驟: 

  • 寫入數據到Buffer
  • 調用flip()方法
  • 從Buffer中讀取數據
  • 調用clear()方法或者compact()方法
當向buffer寫入數據時,buffer會記錄下寫了多少數據。一旦要讀取數據,需要通過flip()方法將Buffer從寫模式切換到讀模式。在讀模式下,可以讀取之前寫入到buffer的所有數據。 

一旦讀完了所有的數據,就需要清空緩衝區,讓它可以再次被寫入。有兩種方式能清空緩衝區:調用clear()或compact()方法。clear()方法會清空整個緩衝區。compact()方法只會清除已經讀過的數據。任何未讀的數據都被移到緩衝區的起始處,新寫入的數據將放到緩衝區未讀數據的後面。 

下面是一個使用Buffer的例子:


import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class NIOFileChannel {
    public static void main(String[] args) throws IOException, InterruptedException {

        RandomAccessFile accessFile = new RandomAccessFile("data.txt","rw");
        FileChannel fileChannel = accessFile.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(50);
        //read 48
        //String  data  int  bool  char  long  float  doub
        //15
        //表示沒有寫完,緩衝區大小有限制,只讀入48,剩下的等讀完,清空緩存區,再次繼續讀入。
        int bytecount = fileChannel.read(byteBuffer);
        while (bytecount!=-1)
        {
            System.out.println("read "+ bytecount);
            byteBuffer.flip();
            bytecount = -1;
        }
        String temp = "";
        while (byteBuffer.hasRemaining())
        {
            char c = (char) byteBuffer.get();
            if(c!='\r'&&c!='\n')
            {
                temp +=c;
            }else
            {
                System.out.print(temp+" ");
                temp = "";
            }
        }
        System.out.println(temp);
        byteBuffer.clear();
        bytecount = fileChannel.read(byteBuffer);
        System.out.println(bytecount);


        //沒讀完繼續讀
        //read 50
        //String  data  int  bool  char  long  float  double
        //13
        //read 13
        //short byte
        //-1

        while (bytecount!=-1)
        {
            System.out.println("read "+ bytecount);
            byteBuffer.flip();
            bytecount = -1;
        }
        temp = "";
        while (byteBuffer.hasRemaining())
        {
            char c = (char) byteBuffer.get();
            if(c!='\r'&&c!='\n')
            {
                temp +=c;
            }else if(!temp.equals(""))
            {
                System.out.print(temp+" ");
                temp = "";
            }
        }
        System.out.println(temp);
        byteBuffer.clear();
        bytecount = fileChannel.read(byteBuffer);
        System.out.println(bytecount);
        accessFile.close();









        //RandomAccessFile accessFile = new RandomAccessFile("data.txt","rw")   ;
        //FileChannel fileChannel = accessFile.getChannel();
        //ByteBuffer buffer = ByteBuffer.allocate(100); //申請100字節的緩衝區
        //int byteRead  = fileChannel.read(buffer);
        //
        //while (byteRead!=-1)
        //{
        //    System.out.println("read"+byteRead);
        //    Thread.sleep(500);
        //    buffer.flip();
        //    byteRead = -1;
        //}
        //
        //while (buffer.hasRemaining())
        //{
        //    System.out.println((char) buffer.get());
        //}
        //buffer.clear();
        //byteRead = fileChannel.read(buffer);
        //accessFile.close();

    }
}

 Buffer的capacity,position和limit 

緩衝區本質上是一塊可以寫入數據,然後可以從中讀取數據的內存。這塊內存被包裝成NIO Buffer對象,並提供了一組方法,用來方便的訪問該塊內存。 

爲了理解Buffer的工作原理,需要熟悉它的三個屬性: 

  • capacity
  • position
  • limit
position和limit的含義取決於Buffer處在讀模式還是寫模式。不管Buffer處在什麼模式,capacity的含義總是一樣的。 

這裏有一個關於capacity,position和limit在讀寫模式中的說明,詳細的解釋在插圖後面。 


capacity 
作爲一個內存塊,Buffer有一個固定的大小值,也叫“capacity”.你只能往裏寫capacity個byte、long,char等類型。一旦Buffer滿了,需要將其清空(通過讀數據或者清除數據)才能繼續寫數據往裏寫數據。 

position 
當你寫數據到Buffer中時,position表示當前的位置。初始的position值爲0.當一個byte、long等數據寫到Buffer後, position會向前移動到下一個可插入數據的Buffer單元。position最大可爲capacity – 1。 
當讀取數據時,也是從某個特定位置讀。當將Buffer從寫模式切換到讀模式,position會被重置爲0。當從Buffer的position處讀取數據時,position向前移動到下一個可讀的位置。 

limit 
在寫模式下,Buffer的limit表示你最多能往Buffer裏寫多少數據。 寫模式下,limit等於Buffer的capacity。 

當切換Buffer到讀模式時, limit表示你最多能讀到多少數據。因此,當切換Buffer到讀模式時,limit會被設置成寫模式下的position值。換句話說,你能讀到之前寫入的所有數據(limit被設置成已寫數據的數量,這個值在寫模式下就是position) 

Buffer的類型 

Java NIO 有以下Buffer類型: 

  • ByteBuffer
  • MappedByteBuffer
  • CharBuffer
  • DoubleBuffer
  • FloatBuffer
  • IntBuffer
  • LongBuffer
  • ShortBuffer
如你所見,這些Buffer類型代表了不同的數據類型。換句話說,就是可以通過char,short,int,long,float 或 double類型來操作緩衝區中的字節。 
MappedByteBuffer 有些特別,在涉及它的專門章節中再講。 

Buffer的分配 
要想獲得一個Buffer對象首先要進行分配。 每一個Buffer類都有一個allocate方法。

  1. ByteBuffer buf = ByteBuffer.allocate(48);
  2. CharBuffer buf = CharBuffer.allocate(1024); 

向Buffer中寫數據 
寫數據到Buffer有兩種方式: 

  • 從Channel寫到Buffer。
  • 通過Buffer的put()方法寫到Buffer裏。
  1. int bytesRead = inChannel.read(buf); //從channel寫
  2. buf.put(127); //通過put方法寫

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class channelWrite {
    // 寫之前數據:
    //String
//data
//int
//bool
//char
//long
//float
//double
//short
//byte
    public static void main(String[] args) throws Exception, InterruptedException
    {
        RandomAccessFile accessFile = new RandomAccessFile("data.txt","rw");
        FileChannel fileChannel = accessFile.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(100);
        byteBuffer.put("hello WebClient this is from WebServer".getBytes());
        byteBuffer.flip();
        int bytecount = fileChannel.write(byteBuffer, 66);
        System.out.println(bytecount);

        ByteBuffer bufferread = ByteBuffer.allocate(200);
        bytecount = fileChannel.read(bufferread);
        StringBuilder stringBuffer=new StringBuilder();
        //4.將Buffer從寫模式變爲可讀模式
        bufferread.flip();
        while (bufferread.hasRemaining()) {
            stringBuffer.append((char) bufferread.get());
        }
        System.out.println("從客戶端接收到的數據:"+stringBuffer);
        byteBuffer.clear();
        bytecount = fileChannel.read(byteBuffer);
        System.out.println(bytecount);

    //    結果:
//38
//從客戶端接收到的數據:String
//data
//int
//bool
//char
//long
//float
//double
//short
//byte
//hello WebClient this is from WebServer
//-1
    }

}

put方法有很多版本,允許你以不同的方式把數據寫入到Buffer中。例如, 寫到一個指定的位置,或者把一個字節數組寫入到Buffer。 更多Buffer實現的細節參考JavaDoc。

flip()方法 
flip方法將Buffer從寫模式切換到讀模式。調用flip()方法會將position設回0,並將limit設置成之前position的值。 
換句話說,position現在用於標記讀的位置,limit表示之前寫進了多少個byte、char等 —— 現在能讀取多少個byte、char等。 
從Buffer中讀取數據 
從Buffer中讀取數據有兩種方式: 

  • 從Buffer讀取數據到Channel。
  • 使用get()方法從Buffer中讀取數據。
  1. //read from buffer into channel.
  2. int bytesWritten = inChannel.write(buf);
  3. byte aByte = buf.get();
get方法有很多版本,允許你以不同的方式從Buffer中讀取數據。例如,從指定position讀取,或者從Buffer中讀取數據到字節數組。更多Buffer實現的細節參考JavaDoc。 

rewind()方法 
Buffer.rewind()將position設回0,所以你可以重讀Buffer中的所有數據。limit保持不變,仍然表示能從Buffer中讀取多少個元素(byte、char等)。 

clear()與compact()方法 
一旦讀完Buffer中的數據,需要讓Buffer準備好再次被寫入。可以通過clear()或compact()方法來完成。 
如果調用的是clear()方法,position將被設回0,limit被設置成 capacity的值。換句話說,Buffer 被清空了。Buffer中的數據並未清除,只是這些標記告訴我們可以從哪裏開始往Buffer裏寫數據。 
如果Buffer中有一些未讀的數據,調用clear()方法,數據將“被遺忘”,意味着不再有任何標記會告訴你哪些數據被讀過,哪些還沒有。 
如果Buffer中仍有未讀的數據,且後續還需要這些數據,但是此時想要先先寫些數據,那麼使用compact()方法。
compact()方法將所有未讀的數據拷貝到Buffer起始處。然後將position設到最後一個未讀元素正後面。limit屬性依然像clear()方法一樣,設置成capacity。現在Buffer準備好寫數據了,但是不會覆蓋未讀的數據。 

mark()與reset()方法 
通過調用Buffer.mark()方法,可以標記Buffer中的一個特定position。之後可以通過調用Buffer.reset()方法恢復到這個position。例如: 
  1. buffer.mark(); //call buffer.get() a couple of times, e.g. during parsing.
  2. buffer.reset(); //set position back to mark.
equals()與compareTo()方法 

可以使用equals()和compareTo()方法比較兩個Buffer。 

equals() 
當滿足下列條件時,表示兩個Buffer相等: 
  • 有相同的類型(byte、char、int等)。
  • Buffer中剩餘的byte、char等的個數相等。
  • Buffer中所有剩餘的byte、char等都相同。
如你所見,equals只是比較Buffer的一部分,不是每一個在它裏面的元素都比較。實際上,它只比較Buffer中的剩餘元素。 

compareTo()方法 
compareTo()方法比較兩個Buffer的剩餘元素(byte、char等), 如果滿足下列條件,則認爲一個Buffer“小於”另一個Buffer: 
  • 第一個不相等的元素小於另一個Buffer中對應的元素。
  • 所有元素都相等,但第一個Buffer比另一個先耗盡(第一個Buffer的元素個數比另一個少)。




轉載

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章