Java NIO之Channel

Java NIO之Buffer 一文介绍过 缓冲区Buffer。Channel是Java NIO的核心组件之一,用于连接源节点和目标节点,负责缓冲区数据的传输,分类如下:

(1)FileChannel,文件通道

(2)SocketChannel和ServerSocketChannel,通过TCP读写网络中的数据

(3)DatagramChannel,通过UDP读写网络中的数据

获取通道的方法:

(1)本地IO:FileInputStream,FileOutputStream,RandomAccessFile实例的getChannel方法

(2)SocketChannel,ServerSocketChannel,DatagramChannel的open()方法

(3)java.nio.file.Files工具类下的newByteChannel方法

下面演示,通过NIO的通道Channel,实现文件的复制操作:

   // 文件复制,使用非直接缓冲区
    public static void testCopyFileByChannel(String srcFileName,String destFileName){
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
             fileInputStream = new FileInputStream(srcFileName);
             fileOutputStream = new FileOutputStream(destFileName);
             // 1. 获取通道
            inChannel = fileInputStream.getChannel();
            outChannel = fileOutputStream.getChannel();

            // 2. 分配指定缓冲区大小
            ByteBuffer buffer = ByteBuffer.allocate(1024);

            // 循环读写
            // 3.向缓冲区写数据
            while (inChannel.read(buffer) != -1){
                // 4.切换为读模式
                buffer.flip();
                // 5.从缓冲区读数据
                outChannel.write(buffer);
                // 6.清空缓冲区
                buffer.clear();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (fileInputStream != null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileOutputStream != null){
                try {
                    fileOutputStream.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();
                }
            }
        }
    }

其实,就是分为了三步:

(1)获取通道

(2)分配缓冲区

(3)读写数据

这种方式,虽然有缓冲区,但是读写速度并不快,因为使用的不是直接缓冲区,关于直接缓冲区和非直接缓冲区可自行了解,简单来说,直接缓冲区,省去了数据在用户态和内核态之间的数据复制过程,所以会比较快,下面是一个使用直接缓冲区的简单示例:

    // 通道之间的数据传输,使用直接缓冲区
    public static void testChannel2Channel() throws IOException {
        // 获取通道
        FileChannel inChannel = FileChannel.open(Paths.get("D:\\1.avi"), StandardOpenOption.READ);
        FileChannel outChannel = FileChannel.open(Paths.get("D:\\2.avi"), StandardOpenOption.READ,StandardOpenOption.WRITE,StandardOpenOption.CREATE);

        // 通过调用 transferTo 或者 transferFrom方法实现复制
//        inChannel.transferTo(0,inChannel.size(),outChannel);
        outChannel.transferFrom(inChannel,0,inChannel.size());
        inChannel.close();
        outChannel.close();
    }

通过大文件的数据传输过程比较,就可以发现,使用直接缓冲区速度快了很多很多

之前也写过一篇文章,Java使用NIO实现大文件下载

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java NIO(New Input Output)是Java SE 1.4中引入的一个新的IO API,它可以提供比传统的Java IO更高效的I/O操作。 在Java NIO中,最核心的概念是Channel(通道)。Channel是用于在Java NIO中进行I/O操作的对象,可以被打开或关闭,并且可以读取或写入数据。 通常情况下,可以通过调用Channel实现读取和写入数据。Channel可以分为以下几类: 1. FileChannel FileChannel用于在文件中读取和写入数据。 在操作FileChannel时,需要首先通过FileInputStream或FileOutputStream获取文件的输入和输出流,然后通过调用getChannel()方法获取FileChannel对象。 示例: ``` FileInputStream fis = new FileInputStream("test.txt"); FileChannel channel = fis.getChannel(); ``` 2. SocketChannel SocketChannel用于通过网络读取和写入数据。 在操作SocketChannel时,需要创建一个SocketChannel对象,并将其连接到一个远程服务器,然后调用read()和write()方法实现数据的读取和写入。 示例: ``` SocketChannel channel = SocketChannel.open(); channel.connect(new InetSocketAddress("www.google.com", 80)); ``` 3. DatagramChannel DatagramChannel用于通过UDP连接读取和写入数据。 在操作DatagramChannel时,需要创建一个DatagramChannel对象,并绑定到一个本地端口号,然后调用read()和write()方法实现数据的读取和写入。 示例: ``` DatagramChannel channel = DatagramChannel.open(); channel.socket().bind(new InetSocketAddress(9999)); ``` 4. ServerSocketChannel ServerSocketChannel用于监听客户端的连接请求。 在操作ServerSocketChannel时,需要创建一个ServerSocketChannel对象,并绑定到一个本地端口号,然后调用accept()方法等待客户端的连接请求。 示例: ``` ServerSocketChannel channel = ServerSocketChannel.open(); channel.socket().bind(new InetSocketAddress(9999)); SocketChannel socketChannel = channel.accept(); ``` 总结来说,ChannelJava NIO库中最重要的概念之一,它提供了各种不同类型的Channel,可以帮助我们轻松地实现不同类型的I/O操作。通常情况下,在进行I/O操作时,我们都需要借助Channel来完成。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值