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
One approach would be to create a File object for target file, and then check if it exists, something like: