关于使用IO流复制文件的办法

思路:通过FileInputStream类的对象将原文件与其对象关联,将原文件内容读取到内存中,然后通过FileOutputStream类的对象将内存中的数据写入到磁盘中

import java.io.*;
public class Test3 {
    public static void method(File source,File copy)
    {
        long time1=System.currentTimeMillis();
        try (InputStream inputStream=new FileInputStream(source);
             OutputStream outputStream=new FileOutputStream(new File(copy,source.getName()))){
            byte[] bytes=new byte[1024*10];
            int i;
            while ((i=inputStream.read(bytes,0,bytes.length))!=-1)//只写一个参数bytes也可
            {
                outputStream.write(bytes,0,i);//形参建议写全
            }
            System.out.println("复制完成");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        long time2=System.currentTimeMillis();
        System.out.println("用时:"+(time2-time1)+"毫秒");
    }

    public static void main(String[] args) {
        String source="D:\\Downloads\\jdk api 1.8_google.CHM";
        String copy="D:\\";
        method(new File(source),new File(copy));
    }
}

在这里插入图片描述
一、inputStream对象将source文件的内容读到内存中,outputStream对象将内存中的数据写入到copy文件中;
二、需要注意,copy文件对象为一个目录,文件并不存在(String copy=“D:\”;),因此在将outputStream对象实例化时,构造器中应新建一个File类的对象,new File(copy,source.getName())
在这里插入图片描述
从API文档中可以看出,File类其中一个构造写法为File(File parent, String child) ,在本例中parent即为copy复制文件,child即为source的name。本例使复制文件同原文件同名。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值