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

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

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(); }

复制文件就轻松搞定了

猜你喜欢

转载自www.cnblogs.com/dayu007/p/10062643.html