Java NIO學(xué)習(xí)筆記-通道&緩沖區(qū)

Java NIO是什么

Java NIO( New IO) 是從Java 1.4版本開始引入的一個新的IO API,可以替代標(biāo)準(zhǔn)的Java IO API。NIO與原來的IO有同樣的作用和目的,但是使用的方式完全不同, NIO支持面向緩沖區(qū)的、基于通道的IO操作。 NIO將以更加高效的方式進行文件的讀寫操作。

Java NIO 與 IO 的主要區(qū)別

IO NIO
面向流(Stream Oriented) 面向緩沖區(qū)(Buffer Oriented)
阻塞IO(Blocking IO) 非阻塞IO(Non Blocking IO)
(無) 選擇器(Selectors)

緩沖區(qū)( Buffer)

一個用于特定基本數(shù)據(jù)類型的容器。由 java.nio 包定義的,所有緩沖區(qū)都是 Buffer 抽象類的子類。Buffer 主要用于與 NIO 通道進行交互,數(shù)據(jù)是從通道讀入緩沖區(qū),從緩沖區(qū)寫入通道中的。Buffer 就像一個數(shù)組,可以保存多個相同類型的數(shù)據(jù)。根據(jù)數(shù)據(jù)類型不同(boolean 除外) ,有以下 Buffer 常用子類:

  • ByteBuffer
  • CharBuffer
  • ShortBuffer
  • IntBuffer
  • LongBuffer
  • FloatBuffer
  • DoubleBuffer

上述 Buffer 類 他們都采用相似的方法進行管理數(shù)據(jù),只是各自管理的數(shù)據(jù)類型不同而已。

緩沖區(qū)的基本屬性
  • 容量 (capacity) :表示 Buffer 最大數(shù)據(jù)容量,緩沖區(qū)容量不能為負(fù),并且創(chuàng)建后不能更改.
  • 限制 (limit):第一個不應(yīng)該讀取或?qū)懭氲臄?shù)據(jù)的索引,即位于 limit 后的數(shù)據(jù)不可讀寫。緩沖區(qū)的限制不能為負(fù),并且不能大于其容量。
  • 位置 (position):下一個要讀取或?qū)懭氲臄?shù)據(jù)的索引。緩沖區(qū)的位置不能為負(fù),并且不能大于其限制.
  • 標(biāo)記 (mark)與重置 (reset):標(biāo)記是一個索引,通過 Buffer 中的 mark() 方法指定 Buffer 中一個特定的 position,之后可以通過調(diào)用 reset()方法恢復(fù)到這個 position.

標(biāo)記、 位置、 限制、 容量遵守以下不變式: 0 <= mark <= position <= limit <= capacity

緩沖區(qū)的數(shù)據(jù)操作

Buffer 所有子類提供了兩個用于數(shù)據(jù)操作的方法: get()與 put() 方法

獲取 Buffer 中的數(shù)據(jù)
  • get() :讀取單個字節(jié)
  • get(byte[] dst):批量讀取多個字節(jié)到 dst 中
  • get(int index):讀取指定索引位置的字節(jié)(不會移動 position)
放入數(shù)據(jù)到 Buffer 中
  • put(byte b):將給定單個字節(jié)寫入緩沖區(qū)的當(dāng)前位置
  • put(byte[] src):將 src 中的字節(jié)寫入緩沖區(qū)的當(dāng)前位置
  • put(int index, byte b):將指定字節(jié)寫入緩沖區(qū)的索引位置(不會移動 position)
public class TestBuffer {

    @Test
    public void test1() {
        //分配指定大小的緩沖區(qū)
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        System.out.println(buffer.position());//0 返回緩沖區(qū)的當(dāng)前位置 position
        System.out.println(buffer.limit());//1024 返回 Buffer 的界限(limit) 的位置
        System.out.println(buffer.capacity());//1024 返回Buffer的capacity 大小
        //將數(shù)據(jù)存入緩沖區(qū)
        buffer.put("abcde".getBytes());
        
        System.out.println(buffer.position());//5
        System.out.println(buffer.limit());//1024
        System.out.println(buffer.capacity());//1024
        //切換到讀取數(shù)據(jù)的模式
        buffer.flip();
        
        System.out.println(buffer.position());//0
        System.out.println(buffer.limit());//5
        System.out.println(buffer.capacity());//1024
        //讀取緩沖區(qū)的數(shù)據(jù)
        byte[] bs = new byte[buffer.limit()];
        buffer.get(bs);
        System.out.println(new String(bs, 0, bs.length));//abcde
        
        System.out.println(buffer.position());//5
        System.out.println(buffer.limit());//5
        System.out.println(buffer.capacity());//1024
        //回到讀模式,可重復(fù)讀數(shù)據(jù)
        buffer.rewind();//將位置設(shè)為為 0, 取消設(shè)置的 mark
        
        System.out.println(buffer.position());//0
        System.out.println(buffer.limit());//5
        System.out.println(buffer.capacity());//1024
        //清空緩沖區(qū),回到最初狀態(tài)。但是緩沖區(qū)的數(shù)據(jù)還在,處于被遺忘狀態(tài)。
        buffer.clear();//清空緩沖區(qū)并返回對緩沖區(qū)的引用
        System.out.println(buffer.position());//0
        System.out.println(buffer.limit());//1024
        System.out.println(buffer.capacity());//1024
    }
    
    @Test
    public void test2() {
        String str = "abcde";
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        buffer.put(str.getBytes());
        
        System.out.println(buffer.position());//5
        System.out.println(buffer.limit());//1024
        System.out.println(buffer.capacity());//1024
        
        buffer.flip();
        
        byte[] bs = new byte[buffer.limit()];
        buffer.get(bs, 0, 2);
        System.out.println(new String(bs, 0, 2));//ab
        
        System.out.println(buffer.position());//2
        System.out.println(buffer.limit());//5
        System.out.println(buffer.capacity());//1024
        //標(biāo)記position的位置
        buffer.mark();
        
        buffer.get(bs, 2, 2);
        System.out.println(new String(bs, 2, 2));//cd
        
        System.out.println(buffer.position());//4
        //重置position的位置到標(biāo)記的地方
        buffer.reset();
        
        System.out.println(buffer.position());//2
        //緩沖區(qū)中是否還有課操作的字節(jié)
        if (buffer.hasRemaining()) {
            //剩余可操作的字節(jié)數(shù)
            System.out.println(buffer.remaining());//3 返回 position 和 limit 之間的元素個數(shù)
        }
    }
    
    @Test
    public void test3() {
        //創(chuàng)建直接緩沖區(qū)
        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
        //判斷是否為直接緩沖區(qū)
        System.out.println(buffer.isDirect());//true
    }
}

直接與非直接緩沖區(qū)

  1. 字節(jié)緩沖區(qū)要么是直接的,要么是非直接的。如果為直接字節(jié)緩沖區(qū),則 Java 虛擬機會盡最大努力直接在此緩沖區(qū)上執(zhí)行本機 I/O操作。也就是說,在每次調(diào)用基礎(chǔ)操作系統(tǒng)的一個本機 I/O 操作之前(或之后),虛擬機都會盡量避免將緩沖區(qū)的內(nèi)容復(fù)制到中間緩沖區(qū)中(或從中間緩沖區(qū)中復(fù)制內(nèi)容)。
  2. 直接字節(jié)緩沖區(qū)可以通過調(diào)用此類的 allocateDirect() 工廠方法來創(chuàng)建。此方法返回的緩沖區(qū)進行分配和取消分配所需成本通常高于非直接緩沖區(qū)。直接緩沖區(qū)的內(nèi)容可以駐留在常規(guī)的垃圾回收堆之外,因此,它們對應(yīng)用程序的內(nèi)存需求量造成的影響可能并不明顯。所以,建議將直接緩沖區(qū)主要分配給那些易受基礎(chǔ)系統(tǒng)的本機 I/O 操作影響的大型、持久的緩沖區(qū)。一般情況下,最好僅在直接緩沖區(qū)能在程序性能方面帶來明顯好處時分配它們。
  3. 直接字節(jié)緩沖區(qū)還可以通過 FileChannel 的 map() 方法將文件區(qū)域直接映射到內(nèi)存中來創(chuàng)建。該方法返回MappedByteBuffer。Java 平臺的實現(xiàn)有助于通過 JNI從本機代碼創(chuàng)建直接字節(jié)緩沖區(qū)。如果以上這些緩沖區(qū)中的某個緩沖區(qū)實例指的是不可訪問的內(nèi)存區(qū)域,則試圖訪問該區(qū)域不會更改該緩沖區(qū)的內(nèi)容,并且將會在訪問期間或稍后的某個時間導(dǎo)致拋出不確定的異常。
  4. 字節(jié)緩沖區(qū)是直接緩沖區(qū)還是非直接緩沖區(qū)可通過調(diào)用其 isDirect() 方法來確定。提供此方法是為了能夠在性能關(guān)鍵型代碼中執(zhí)行顯式緩沖區(qū)管理。

通道Channel

通道表示打開到 IO 設(shè)備(例如:文件、套接字)的連接。若需要使用 NIO 系統(tǒng),需要獲取用于連接 IO 設(shè)備的通道以及用于容納數(shù)據(jù)的緩沖區(qū)。然后操作緩沖區(qū),對數(shù)據(jù)進行處理。Channel 負(fù)責(zé)傳輸, Buffer 負(fù)責(zé)存儲。通道是由 java.nio.channels 包定義的。 Channel 表示 IO 源與目標(biāo)打開的連接。Channel 類似于傳統(tǒng)的“流”。只不過 Channel本身不能直接訪問數(shù)據(jù), Channel 只能與Buffer 進行交互。

Java 為 Channel 接口提供的最主要實現(xiàn)類
  • FileChannel:用于讀取、寫入、映射和操作文件的通道。
  • DatagramChannel:通過 UDP 讀寫網(wǎng)絡(luò)中的數(shù)據(jù)通道。
  • SocketChannel:通過 TCP 讀寫網(wǎng)絡(luò)中的數(shù)據(jù)。
  • ServerSocketChannel:可以監(jiān)聽新進來的 TCP 連接,對每一個新進來的連接都會創(chuàng)建一個 SocketChannel。
獲取通道

獲取通道的一種方式是對支持通道的對象調(diào)用getChannel() 方法。支持通道的類如下:

  • FileInputStream
  • FileOutputStream
  • RandomAccessFile
  • DatagramSocket
  • Socket
  • ServerSocket

獲取通道的其他方式是使用 Files 類的靜態(tài)方法 newByteChannel() 獲取字節(jié)通道?;蛘咄ㄟ^通道的靜態(tài)方法 open() 打開并返回指定通道。

通道的數(shù)據(jù)傳輸
//通道用于源節(jié)點與目標(biāo)節(jié)點之間的連接,在NIO中負(fù)責(zé)緩沖區(qū)中數(shù)據(jù)的傳輸。
//Channel本身不存儲數(shù)據(jù),需要配合緩沖區(qū)進行數(shù)據(jù)傳輸
/**
 * 通道的主要實現(xiàn)類
 * java.nio.channels.Channel接口
 *      |--FileChannel
 *      |--SocketChannel
 *      |--ServerSocketChannel
 *      |--DatagramChannel
 *
 * 獲取通道
 * 1.Java針對支持通道的類提供了getChannel()方法
 *      本地IO:
 *          FileInputStream/FileOutputStream
 *          RandomAccessFile
 * 
 *      網(wǎng)絡(luò)IO:
 *          Socket
 *          ServerSocket
 *          DatagramSocket
 * 
 * 2.在JDK1.7中NIO.2針對各個通道提供了靜態(tài)方法open()
 * 3.在JDK1.7中NIO.2的Files工具類的newByteChannel()
 */


public class TestChannel {
    //利用通道完成文件的復(fù)制(非直接緩沖區(qū))
    @Test
    public void test1() {
        //26088
        //6479
        //6587
        //6464
        long start = System.currentTimeMillis();
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        try {
            fileInputStream = new FileInputStream("E:\\BaiduYunDownload\\juc.zip");
            fileOutputStream = new FileOutputStream("F:\\juc_copy2.zip");
            //獲取通道
            inChannel = fileInputStream.getChannel();
            outChannel = fileOutputStream.getChannel();
            //分配指定大小的緩沖區(qū)
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            //將通道中的數(shù)據(jù)存入緩沖區(qū)
            while (inChannel.read(buffer) != -1) {
                //切換成讀取數(shù)據(jù)模式
                buffer.flip();
                //將緩沖區(qū)中的數(shù)據(jù)寫入通道中
                outChannel.write(buffer);
                //清空緩沖區(qū)
                buffer.clear();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            //關(guān)閉通道 省略if判斷
            outChannel.close();
            inChannel.close();
            //關(guān)閉流
            fileOutputStream.close();
            fileInputStream.close();
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }
    
    @Test
    public void test2() throws IOException {
        //1190
        //5144
        //5932
        //1316
        //1126
        //998
        //1242
        long start = System.currentTimeMillis();
        //使用直接緩沖區(qū)完成文件的復(fù)制(內(nèi)存映射文件)
        //只有ByteBuffer支持直接緩沖區(qū)
        FileChannel inChannel = FileChannel.open(Paths.get("E:\\BaiduYunDownload\\", "juc.zip"), StandardOpenOption.READ);
        //StandardOpenOption.CREATE_NEW若存在則報錯
        //StandardOpenOption.CREATE若存在則覆蓋
        FileChannel outChannel = FileChannel.open(Paths.get("F:/", "juc-3.zip"), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
        //內(nèi)存映射文件。緩沖區(qū)在物理內(nèi)存中。
        MappedByteBuffer inMappedByteBuffer = inChannel.map(MapMode.READ_ONLY, 0, inChannel.size());
        MappedByteBuffer outMappedByteBuffer = outChannel.map(MapMode.READ_WRITE, 0, inChannel.size());
        
        //直接對緩沖區(qū)進行數(shù)據(jù)讀寫操作
        byte[] dst = new byte[inMappedByteBuffer.limit()];
        inMappedByteBuffer.get(dst);
        outMappedByteBuffer.put(dst);
        
        inChannel.close();
        outChannel.close();
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }
    
    @Test
    public void test3() throws IOException {
    //將數(shù)據(jù)從源通道傳輸?shù)狡渌?Channel 中
        //729
        //684
        //601
        //706
        //625
        long start = System.currentTimeMillis();
        FileChannel inChannel = FileChannel.open(Paths.get("E:\\BaiduYunDownload\\", "juc.zip"), StandardOpenOption.READ);
        FileChannel outChannel = FileChannel.open(Paths.get("F:/", "juc-4.zip"), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
        //通道之間的數(shù)據(jù)傳輸
        //inChannel.transferTo(0, inChannel.size(), outChannel);
        outChannel.transferFrom(inChannel, 0, inChannel.size());
        inChannel.close();
        outChannel.close();
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }
    
    @Test
    public void test4() throws IOException {
        RandomAccessFile randomAccessFile1 = new RandomAccessFile("E:/a.txt", "rw");
        //獲取通道
        FileChannel fileChannel1 = randomAccessFile1.getChannel();
        //分配指定大小的緩沖區(qū)
        ByteBuffer buffer1 = ByteBuffer.allocate(100);
        ByteBuffer buffer2 = ByteBuffer.allocate(1024);
        //分散讀取,從 Channel 中讀取的數(shù)據(jù)“分散” 到多個 Buffer 中
        ByteBuffer[] buffers = {buffer1, buffer2};
        fileChannel1.read(buffers);
        for (int i = 0; i < buffers.length; i++) {
            buffers[i].flip();
        }
        System.out.println(new String(buffers[0].array(), 0, buffers[0].limit()));
        System.out.println("-------------------");
        System.out.println(new String(buffers[1].array(), 0, buffers[1].limit()));
        //聚集寫入,將多個 Buffer 中的數(shù)據(jù)“聚集”到 Channel
        RandomAccessFile randomAccessFile2 = new RandomAccessFile("E:/b.txt", "rw");
        FileChannel fileChannel2 = randomAccessFile2.getChannel();
        fileChannel2.write(buffers);
    }
    
    @Test
    public void test5() {
        /**
         * 編碼:字符串->字節(jié)數(shù)組
         * 解碼:字節(jié)數(shù)組->字符串
         */
        //獲取所有支持的字符集
        SortedMap<String, Charset> availableCharsets = Charset.availableCharsets();
        Set<Entry<String, Charset>> set = availableCharsets.entrySet();
        for (Entry<String, Charset> entry: set) {
            System.out.println(entry.getKey() + "--" + entry.getValue());
        }
    }
    
    @Test
    public void test6() throws CharacterCodingException {
        Charset charset = Charset.forName("GBK");
        //編碼器
        CharsetEncoder charsetEncoder = charset.newEncoder();
        //解碼器
        CharsetDecoder charsetDecoder = charset.newDecoder();
        CharBuffer charBuffer = CharBuffer.allocate(1024);
        charBuffer.put("你好");
        charBuffer.flip();
        //編碼
        ByteBuffer byteBuffer = charsetEncoder.encode(charBuffer);
        
        for (int i = 0; i < 4; i++) {
            //字節(jié)數(shù)組
            System.out.println(byteBuffer.get());
        }
        //切換到讀模式
        byteBuffer.flip();
        //解碼
        CharBuffer charBuffer2 = charsetDecoder.decode(byteBuffer);
        System.out.println(charBuffer2.toString());
    }
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容