io文件拷贝

使用io和nio进行文件拷贝

1、io

    @Test
    public void iotest() throws Exception {
        InputStream in = new FileInputStream("C:\\shit.txt");
        OutputStream out = new FileOutputStream("C:\\shit2.txt");
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = in.read(bytes)) > 0) {
            out.write(bytes, 0, len);
        }
        in.close();
        out.close();
    }

2、nio

    @Test
    public void nioTest() throws Exception {
        FileInputStream in = new FileInputStream("C:\\shit.txt");
        FileOutputStream out = new FileOutputStream("C:\\shit3.txt");
        FileChannel inChannel = in.getChannel();
        FileChannel outChannel = out.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        byteBuffer.clear();
        inChannel.read(byteBuffer);
        byteBuffer.flip();
        outChannel.write(byteBuffer);
        in.close();
        out.close();
    }

3、InputStream中的read方法

 /**
     * @param b   缓冲数组
     * @param off 读取位置
     * @param len 读取长度
     * @return
     * @throws IOException
     */
    public int read(byte b[], int off, int len) throws IOException {
        //缓冲数组为空时,直接抛异常
        if (b == null) {
            throw new NullPointerException();
        }
        //读取位置小于0或者
        //读取长度小于0或者
        //读取长度大于可读取的长度
        //都会抛出数组越界
        else if (off < 0 || len < 0 || len > b.length - off) {
            throw new IndexOutOfBoundsException();
        }
        //读取长度等于0,返回0
        else if (len == 0) {
            return 0;
        }
        //读取8个二进制位,并转换成十进制
        int c = read();
        //-1代表没有可读取的二进制数
        if (c == -1) {
            return -1;
        }
        //把读出来的十进制数c转为byte类型
        // 赋值到缓冲数组的起始位置
        //这几步是为了保证读取的起始位置有值
        b[off] = (byte) c;
        //循环读取的长度
        int i = 1;
        try {
            for (; i < len; i++) {
                //读取,赋值,重复之前的操作
                c = read();
                if (c == -1) {
                    break;
                }
                b[off + i] = (byte) c;
            }
        } catch (IOException ee) {
        }
        //读取完毕,i的值应该等于len
        return i;
    }


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值