文件复制Files.copy(source, target, options)

本文详细介绍了Java中Files类的copy()方法,该方法提供了一种简便的文件复制方式,相较于流读写更为高效。文章通过实例展示了如何使用此方法进行文件复制,并提供了注意事项,如目标文件路径的预先检查和创建。

发现了一个复制文件的源码自带的方法,比起流读写的方法更简单了

Files.copy(source, target, options)

源码部分

  public static Path copy(Path source, Path target, CopyOption... options)
        throws IOException
    {
        FileSystemProvider provider = provider(source);
        if (provider(target) == provider) {
            // same provider
            provider.copy(source, target, options);
        } else {
            // different providers
            CopyMoveHelper.copyToForeignTarget(source, target, options);
        }
        return target;
    }

 

用法也很简单,源文件,目标文件File 获取path,在传入方法,options可以不传值,参数可以忽略。

例如:D:/a.txt文件要复制到E:/xx/b.txt中,

就要先将两文件的path得到,这里要求目标文件b.txt文件不存在,存在了就爆错了。

但是目标文件的路径必须要有,源代码方法中没有创建dir的方法。

eg.

      //要确认拷贝的路径存在
        File destDir = new File("E:/xx");
        if(!(destDir.exists()&& destDir.isDirectory())) {
            destDir.mkdirs();
        }
     File source
= new File("D:/a.txt"); File dest = new File("E:/xx/b.txt"); try{ Files.copy(source.toPath(), dest.toPath()); } catch (IOException e){ // TODO Auto-generated catch block e.printStackTrace(); }

复制文件就轻松搞定了

转载于:https://www.cnblogs.com/dayu007/p/10062643.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值