Copy files from one directory to another without replacement

血红的双手。 提交于 2019-12-11 10:03:07

问题


So I cannot seem to find a suitable way to copy files from one directory to another without overwriting a file with the same name. All existing java methods I have seen overwrite existing files(FileUtils) or throw an exception(Files nio)

For example if I have a file struct like:

├───srcDir
│   ├───this.txt
│   ├───hello.txt
│   ├───main.java

├───destDir
│   ├───this.txt

I want to copy over hello.txt and main.java however I do not want to copy/update/replace this.txt

I am trying this approach:

try{
    DirectoryStream<path> files = Files.newDirecotryStream(FileSystems.getDefault().getPath(srcDir);
    for(Path f : files)
        if(Files.notExists(f))
            Files.copy(f, Paths.get(targetDir).resolve(f.getFileName()));

}catch(IOException e){
    e.printStackTrace();
}

Which doesn't work obviously because I'm just checking if f does not exist in in the src directory which of course it exists because that's where I'm pulling from.

I really want to say something like if(Files.notExists(f) in target directory) but I'm not sure if that's possible.

So is this the an appropriate approach? Is there a better way? Thanks


回答1:


One approach would be to create a File object for target file, and then check if it exists, something like:

for(Path f : files) {
    String targetPath = targetDir + System.getProperty("file.separator") + f.getFileName;
    File target = new File(targetPath);
    if(!target.exists())
        Files.copy(f, Paths.get(targetDir).resolve(f.getFileName()));
}


来源:https://stackoverflow.com/questions/34363892/copy-files-from-one-directory-to-another-without-replacement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!