繁体   English   中英

仅当to目录java中不存在文件时,如何复制文件

[英]how to copy a file only if it does not exist in the to directory java

我已经进行了彻底的搜索,并且可以肯定没有人问过这个问题。 但是,这可能是因为这样做完全是错误的方法。 我曾经写过一个有效的Java程序,该程序将文件从一个目录复制到另一个目录。 如果文件已经存在于相应的目录中,它将被捕获并被重新命名。 我想将此程序用于其他应用程序,为此,我希望它在捕获到异常时不执行任何操作,只需继续执行该程序而不复制该文件即可。 我将使用它来修复大约18gb的文件,如果该文件在捕获到异常时甚至打印了一个字符,效率将非常低下。 这是我到目前为止的代码:

import java.nio.file.*;
import java.io.IOException;
public class Sync
{
    public static void main(String[] args)
    {
        String from=args[0];
        Path to=FileSystems.getDefault().getPath(args[1]);
        copyFiles(from, to);
    }
    public static void copyFiles(String from, Path to)
    {
        try(DirectoryStream<Path> files= Files.newDirectoryStream(FileSystems.getDefault().getPath(from)))
        {
            for(Path f:files)
            {
                Files.copy(f, to.resolve(f.getFileName()));
                System.out.println(" "+f.getFileName()+" copied ");
            }
        }
        catch(FileAlreadyExistsException e)
        {
            //not sure
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }   
    }
}

有没有一种方法可以使用FileAlreadyExistsExcpetion来做到这一点?

我不会使用try / catch来执行用户逻辑,从编程的角度来看这是错误的,而且效率也不高。 我要做的是检查文件是否存在,在这种情况下,请跳过复制操作或执行任何您想执行的操作

for(Path f:files)
{
   //here use Files.exists(Path path, LinkOption... options)
   Files.copy(f, to.resolve(f.getFileName()));
   System.out.println(" "+f.getFileName()+" copied ");
}

这里是文件docs: http : //docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html祝你好运

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM