Java IO學習總結(四)

來源:互聯網
上載者:User

標籤:ace   基礎資料型別 (Elementary Data Type)   []   ann   cat   system   輸出資料流   檔案的   第一個   

一、NIO

      NIO採用記憶體對應檔的方式來處理輸入輸出資料流,將檔案或者檔案的一段區域對應到記憶體中,這樣就可以像訪問記憶體一樣訪問檔案,處理速度比傳統的輸入輸出資料流要快。最主要的兩個核心對象是Channel(通道)和Buffer(緩衝)。

1)Buffer

     Buffer是一個抽象類別,最主要的實作類別是ByteBuffer,其他基礎資料型別 (Elementary Data Type)都有對應的buffer類。常用ByteBuffer和CharBuffer;

     建立一個Buffer對象,通過static XXBuffer allocate(int capacity)方法,capacity代表容量。

     Buffer中主要有三個重要的概念,容量(capacity)、界限(limit)和位置(position)

     容量:表示緩衝區的最大資料容量,不可以為負值,建立後不可以改變。

     界限:表示資料不可以被讀出或者寫入的緩衝區索引位置。

     位置:表示下一個可以被讀出或者寫入的緩衝區位置索引,當建立一個buffer對象之後,position為0,從中讀取兩條資料之後,position則為2,指向buffer中的第三個資料位元置。寫入時類似,position自動向後移動位置。

     Buffer中兩個重要方法:flip()和clear();執行flip()方法之後,limit移動到position位置,position置為0,為輸出資料做好準備,;執行clear()方法之後,limit移動到capacity位置,position位置置為0,為寫入資料做好準備。

Buffer常用操作範例程式碼:

public class BufferTest {    public static void main(String[] args) {        // 建立Buffer        CharBuffer buff = CharBuffer.allocate(10);                // 初始化時:position位置為0,limit位置等於capacity        System.out.println("緩衝區容量:" + buff.capacity());        System.out.println("初始化position位置:" + buff.position());        System.out.println("初始化limit位置:" + buff.limit());                // 向緩衝區中放入三條資料        buff.put(‘A‘);        buff.put(‘B‘);        buff.put(‘C‘);        // 此時position位置為3,limit位置等於capacity        System.out.println("裝載資料時position位置:" + buff.position());        System.out.println("裝載資料時limit位置:" + buff.limit());                // 裝載資料結束        buff.flip();        // 查看此時position位置為0,limit位置為3        System.out.println("裝載資料完成position位置:" + buff.position());        System.out.println("裝載資料完成limit位置:" + buff.limit());                // 取出資料,只有使用buff.get()方法時,position自動向後移動位置,使用buff.get(X)position位置不變。        System.out.println("取出第一個資料" + buff.get());        System.out.println("取出資料position位置:" + buff.position());                // 取出資料完成        buff.clear();        // 查看此時position位置為0,limit位置等於capacity        System.out.println("取出資料完成position位置:" + buff.position());        System.out.println("取出資料完成limit位置:" + buff.limit());    }}

2)Channel

     Channel類似於傳統的流對象,可以直接將指定檔案的部分或者全部映射成Buffer,程式不能直接存取Channel,必須通過Buffer互動;所有的Channel都不能通過構造器來直接建立,而是通過傳統的節點InputStream、OutStream的getChannel()的方法返回對於的Channel。

     Channel有三個主要的方法,map()、read()和write(),map()方法用於將Channel中資料對應成ByteBuffer.

範例程式碼

public class ChannelTest {    public static void main(String[] args) {        try {            // 建立檔案            File file = new File("d:\\test.txt");                        // 建立輸入和輸出Channel            FileChannel fic = new FileInputStream(file).getChannel();                FileChannel foc = new FileOutputStream("d:\\channel.txt").getChannel();                        // 將檔案內容全部映射為ByteBuffer            MappedByteBuffer buffer = fic.map(MapMode.READ_ONLY, 0, file.length());            // 將buffer中資料之間輸出到FileChannel中            foc.write(buffer);            // 初始化緩衝區            buffer.clear();                        // 建立解碼器用於buffer轉換            Charset charset = Charset.forName("GBK");            CharsetDecoder cd = charset.newDecoder();                        // 將byteBuffer轉換為charBuffer用於資料輸出展示            CharBuffer charbuff = cd.decode(buffer);            System.out.println("資料為:" + charbuff);                    } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }}

另外一種讀取方式

public class ChannelTest1 {    public static void main(String[] args) {        try {            File file = new File("d:\\test.txt");            FileChannel fci = new FileInputStream(file).getChannel();                        // 定義buffer            ByteBuffer buff = ByteBuffer.allocate(256);                        while(fci.read(buff) != -1){                // 鎖定快取區域,防止讀取null                buff.flip();                // 建立解碼器轉換為charbuffer輸出                Charset charset = Charset.forName("GBK");                CharsetDecoder decode = charset.newDecoder();                System.out.println(decode.decode(buff));                                // 資料讀取完之後,初始化緩衝區                buff.clear();            }        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }    }}

Java IO學習總結(四)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.