Java NIO(4) - 通道(1)

3.6 通道(channel)簡介

通道(Channel):由 java.nio.channels 包定的毅舆。Channel 表示 IO 源與目標(biāo)打開的連接。Channel 類似于傳統(tǒng)的“流”踪危。只不過 Channel本身不能直接訪問數(shù)據(jù),Channel 只能與Buffer 進行交互

3.7 通道模型

image.png
image.png
image.png

3.8 通道(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

3.8.1 獲取通道

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

  • FileInputStream

  • FileOutputStream

  • RandomAccessFile

  • DatagramSocket

  • Socket

  • ServerSocket

獲取通道的其他方式是使用 Files 類的靜態(tài)方法 newByteChannel() 獲取字節(jié)通道∶喝梗或者通過通道的靜態(tài)方法 open() 打開并返回指定通道。

3.8.2 通道的數(shù)據(jù)傳輸

  • 將 Buffer 中數(shù)據(jù)寫入 Channel
image.png
  • 從 Channel 讀取數(shù)據(jù)到 Buffer
image.png

1. 利用通道完成文件的復(fù)制(非直接緩沖區(qū))

    /**
     * 利用通道完成文件的復(fù)制(非直接緩沖區(qū))
     */
    @Test
    public void test01() {
        FileInputStream fis = null;
        FileOutputStream fos = null;

        //1. 獲取通道
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        try {
            fis = new FileInputStream("d:/1.mp4");
            fos = new FileOutputStream("d:/2.mp4");

            inChannel = fis.getChannel();
            outChannel = fos.getChannel();

            //2.分配指定大小的緩沖區(qū)
            ByteBuffer buf = ByteBuffer.allocate(1024);

            //3.將通道的數(shù)據(jù)存在緩沖區(qū)中
            while (inChannel.read(buf) != -1) {
                //切換讀數(shù)據(jù)模式
                buf.flip();
                //4.將緩沖區(qū)的數(shù)據(jù)寫到通道中
                outChannel.write(buf);
                buf.clear();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                ;
            }

            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                ;
            }

            if (inChannel != null) {
                try {
                    inChannel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                ;
            }

            if (outChannel != null) {
                try {
                    outChannel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                ;
            }
        }
    }

2. 使用直接緩沖區(qū)完成文件的復(fù)制(內(nèi)存映射文件) ps:不推薦使用

    /**
     * 使用直接緩沖區(qū)完成文件的復(fù)制(內(nèi)存映射文件)
     */
    @Test
    public void test02() {
        //1.獲取通道
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        
        //2.內(nèi)存映射文件
        MappedByteBuffer inMapperBuf = null;
        MappedByteBuffer outMapperBuf = null;
        
        try {
            inChannel = FileChannel.open(Paths.get("d:/1.mp4"), 
                    //讀
                    StandardOpenOption.READ);
            
            outChannel = FileChannel.open(Paths.get("d:/3.mp4"), 
                    //讀
                    StandardOpenOption.READ, 
                    //創(chuàng)建
                    StandardOpenOption.CREATE_NEW, 
                    //寫
                    StandardOpenOption.WRITE);
            //直接對緩沖區(qū)進行數(shù)據(jù)的讀寫操作
            byte[] dst = new byte[inMapperBuf.limit()];
            inMapperBuf.get(dst);
            outMapperBuf.put(dst);
            
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inChannel != null) {
                try {
                    inChannel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outChannel != null) {
                try {
                    outChannel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

3.通道之間的數(shù)據(jù)傳輸(直接緩沖區(qū)) transferFrom/transferTo

    /**
     * 通道之間的數(shù)據(jù)傳輸(直接緩沖區(qū))
     */
    @Test
    public void test03() {
        //1.獲取通道
        FileChannel inChannel = null;
        FileChannel outChannel = null;

        try {
            inChannel = FileChannel.open(Paths.get("d:/1.mp4"));
            outChannel = FileChannel.open(Paths.get("d:/4.mp4"),
                    StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE);
            //二者選其一,注意選api
//            inChannel.transferTo(0, inChannel.size(), outChannel);
            outChannel.transferFrom(inChannel, 0, inChannel.size());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inChannel != null) {
                try {
                    inChannel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outChannel != null) {
                try {
                    outChannel.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末题翰,一起剝皮案震驚了整個濱河市诈胜,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌焦匈,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,183評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件累魔,死亡現(xiàn)場離奇詭異够滑,居然都是意外死亡,警方通過查閱死者的電腦和手機版述,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,850評論 3 399
  • 文/潘曉璐 我一進店門梯澜,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人渴析,你說我怎么就攤上這事∨亓疲” “怎么了?”我有些...
    開封第一講書人閱讀 168,766評論 0 361
  • 文/不壞的土叔 我叫張陵午磁,是天一觀的道長。 經(jīng)常有香客問我昧辽,道長,這世上最難降的妖魔是什么搅荞? 我笑而不...
    開封第一講書人閱讀 59,854評論 1 299
  • 正文 為了忘掉前任框咙,我火速辦了婚禮,結(jié)果婚禮上喇嘱,老公的妹妹穿的比我還像新娘。我一直安慰自己者铜,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 68,871評論 6 398
  • 文/花漫 我一把揭開白布悔据。 她就那樣靜靜地躺著俗壹,像睡著了一般。 火紅的嫁衣襯著肌膚如雪绷雏。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,457評論 1 311
  • 那天坤检,我揣著相機與錄音期吓,去河邊找鬼早歇。 笑死讨勤,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的潭千。 我是一名探鬼主播,決...
    沈念sama閱讀 40,999評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼屉来,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了茄靠?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,914評論 0 277
  • 序言:老撾萬榮一對情侶失蹤账嚎,失蹤者是張志新(化名)和其女友劉穎儡蔓,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體喂江,經(jīng)...
    沈念sama閱讀 46,465評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡旁振,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,543評論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了吉嚣。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,675評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡尝哆,死狀恐怖甜攀,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情规阀,我是刑警寧澤,帶...
    沈念sama閱讀 36,354評論 5 351
  • 正文 年R本政府宣布歧胁,位于F島的核電站,受9級特大地震影響喊巍,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜玄糟,卻給世界環(huán)境...
    茶點故事閱讀 42,029評論 3 335
  • 文/蒙蒙 一袄秩、第九天 我趴在偏房一處隱蔽的房頂上張望逢并。 院中可真熱鬧郭卫,春花似錦砍聊、人聲如沸贰军。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,514評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至许饿,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間陋率,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,616評論 1 274
  • 我被黑心中介騙來泰國打工瓦糟, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留赴蝇,地道東北人。 一個月前我還...
    沈念sama閱讀 49,091評論 3 378
  • 正文 我出身青樓扯再,卻偏偏與公主長得像,于是被迫代替她去往敵國和親斋竞。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,685評論 2 360