io/nio

对于io操作我们并不陌生,常见的文件处理流程都有IO操作。

先来了解一下NIO。NIO就是多路复用的IO,它主要是由selector,channel和buffer组成,selector可以叫做多路复用选择器,channel是传输数据的管道,buffer是存储数据的缓冲区。下面的图表示的是这三者之间的关系。

一个selector可以监听多个Channel。

Channel和IO中的stream是一个等级的,例如inputStream,outputStream,不同的是stream是单向的 ,Channel是双向的,它既可以进行读操作也能进行写操作。常见的channel有一下几种,SocketChannel,ServerSocketChannel,DatagramChannel和FileChannel。

Buffer就是一个存放数据的容器,是一个连续的数组。在NIO中buffer是一个顶层的父类,它的子类主要有ByteBuffer、IntBuffer、 CharBuffer、 LongBuffer、 DoubleBuffer、FloatBuffer,ShortBuffer。

我们用代码来实现一下NIO的文件操作(transferTo):

 public static void fileChannelCopy(String sfPath, String tfPath) {

        File sf = new File(sfPath);
        File tf = new File(tfPath);
        FileInputStream fi = null;
        FileOutputStream fo = null;
        FileChannel in = null;
        FileChannel out = null;
        try{
            fi = new FileInputStream(sf);
            fo = new FileOutputStream(tf);
            in = fi.getChannel();//得到对应的文件通道
            out = fo.getChannel();//得到对应的文件通道
            in.transferTo(0, in.size(), out);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                fi.close();
                in.close();
                fo.close();
                out.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

再看下传统io的文件复制操作:

private static void traditionalCopy(String sourcePath, String destPath) throws Exception {
        File source = new File(sourcePath);
        File dest = new File(destPath);
        if (!dest.exists()) {
            dest.createNewFile();
        }
        FileInputStream fis = new FileInputStream(source);
        FileOutputStream fos = new FileOutputStream(dest);
        byte[] buf = new byte[1024];
        int len = 0;
        while ((len = fis.read(buf)) != -1) {
            fos.write(buf, 0, len);
        }
        fis.close();
        fos.close();
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值