将文件从一个目录复制到另一个目录而无需替换 [英] Copy files from one directory to another without replacement
问题描述
因此,我似乎找不到不覆盖同名文件的将文件从一个目录复制到另一个目录的合适方法.我见过的所有现有Java方法都会覆盖现有文件(FileUtils)或引发异常(Files nio)
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
我想复制hello.txt
和main.java
,但是我不想复制/更新/替换this.txt
I want to copy over hello.txt
and main.java
however I do not want to copy/update/replace this.txt
我正在尝试这种方法:
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();
}
显然那是行不通的,因为我只是检查src目录中是否不存在f
,因为我要从中提取f
当然存在?
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.
我真的很想说if(Files.notExists(f) in target directory)
之类的话
但我不确定是否可行.
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
推荐答案
一种方法是为目标文件创建File对象,然后检查其是否存在,例如:
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()));
}
这篇关于将文件从一个目录复制到另一个目录而无需替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!