Copy files from one directory to another without r

2019-08-11 07:10发布

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条回答
放荡不羁爱自由
2楼-- · 2019-08-11 08:03

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()));
}
查看更多
登录 后发表回答