教育行業(yè)A股IPO第一股(股票代碼 003032)

全國(guó)咨詢(xún)/投訴熱線(xiàn):400-618-4000

Channel是什么?FileChannel類(lèi)的常用方法

更新時(shí)間:2023年08月14日18時(shí)15分 來(lái)源:傳智教育 瀏覽次數(shù):

好口碑IT培訓(xùn)

Channel 是一個(gè)接口對(duì)象,它類(lèi)似于傳統(tǒng)的流對(duì)象,但與傳統(tǒng)的流對(duì)象又有些不同,具體表現(xiàn)如下:

• Channel可以異步地執(zhí)行I/O讀寫(xiě)操作。

• Channel的讀寫(xiě)操作是雙向的,既可以從 Channel中讀取數(shù)據(jù),又可以寫(xiě)數(shù)據(jù)到Channel,而流的讀寫(xiě)操作通常都是單向的。

• Channel可以直接將指定文件的部分或者全部直接映射成 Buffer。

• Channel只能與Buffer進(jìn)行交互,程序不能直接讀寫(xiě)Channel中的數(shù)據(jù)。

要使用 Channel,就需要使用它的實(shí)現(xiàn)類(lèi)。在 java.nio.channels 包中,提供了很多Channel接口的實(shí)現(xiàn)類(lèi),包括 DatagramChannel、FileChannel、Pipe.SinkChannel、Pipe.SourceChannel,ServerSocketChannel,SocketChannel等。其中 DatagramChannel用于支持UDP網(wǎng)絡(luò)通信,F(xiàn)ileChannel 用于從文件中讀寫(xiě)數(shù)據(jù),Pipe.SinkChannel和 PipeSourceChannel用于支持線(xiàn)程之間的通信,ServerSocketChannel和SocketChannel用于支持TCP網(wǎng)絡(luò)通信。這里將主要講解 FileChannel的使用。

Channel對(duì)象并不是通過(guò)構(gòu)造方法來(lái)創(chuàng)建的,而是通過(guò)傳統(tǒng)I/O的getChannel()方法來(lái)獲取對(duì)應(yīng)的Channel。不同的流所獲取的 Channel 是不同的,例如 FleInputStream和FileOutputStream獲取的是 FileChannel,同時(shí)還可以使用RandomAccessFile 獲取該對(duì)象而 PipedInputStream 和 PipedOutputStream 所獲得的是 Pipe. SinkChannel 和 PipeSourceChannel。

FileChannel類(lèi)可以實(shí)現(xiàn)常用的讀寫(xiě)操作,在類(lèi)中提供了很多專(zhuān)門(mén)用于操作文件的方注 其常用方法如表所示。

了解了FileChannel類(lèi)的常用方法及其功能后,下面通過(guò)一個(gè)文件拷貝的案例,來(lái)演示FileChannel的使用,如下所示。

import java .1 o.*;
importjava.nio.channels.*;
public class Example19 {
    public static void main(String[] args) throws Exception {
        //創(chuàng)建RandomAccessFile對(duì)象,指定源文件
        RandomAccessFile infile = new RandomAccessFile("source/src.jpg", "rw")
        //獲取讀取源文件 Filehannel 通道
        FileChannel inChannel = infile.getChannel();
        //創(chuàng)建RandomAccessFile對(duì)象,指定目標(biāo)文件
        RandomAccessFile outfile = new RandomAccessFile("target/dest.jpg", "rw");
        //獲取復(fù)制目標(biāo)文件 Filechannel通道
        FileChanneloutChannel = outfile.getChannel();
        //使用transferTo(方法進(jìn)行整體復(fù)制
        long transferTo = inChannel.transferTo(0, inChannel.size() outChannel);
        if (transferTo > 0) {
            System.out.printIn("復(fù)制成功!");
        }
        //關(guān)閉資源
        infile.close();
        inChannel.close();
        outfile.close();
        outChannel.close();
    }
}
0 分享到:
和我們?cè)诰€(xiàn)交談!