[英]Copy files from one directory to another without replacement
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) 我见过的所有现有Java方法都会覆盖现有文件(FileUtils)或引发异常(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
我想复制hello.txt
和main.java
但是我不想复制/更新/替换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. 这显然不起作用,因为我只是检查f
是否在src目录中不存在,因为它是我从那里提取的,所以它当然存在。
I really want to say something like if(Files.notExists(f) in target directory)
but I'm not sure if that's possible. 我真的很想说类似if(Files.notExists(f) in target directory)
但我不确定是否可行。
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: 一种方法是为目标文件创建一个File对象,然后检查它是否存在,例如:
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()));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.