将文件从一个目录复制到另一个目录而不进行替换
Copy files from one directory to another without replacement
所以我似乎无法找到一种合适的方法来将文件从一个目录复制到另一个目录而不覆盖同名文件。我见过的所有现有 java 方法都会覆盖现有文件 (FileUtils) 或抛出异常 (Files nio)
例如,如果我有一个像这样的文件结构:
├───srcDir
│ ├───this.txt
│ ├───hello.txt
│ ├───main.java
├───destDir
│ ├───this.txt
我想复制 hello.txt
和 main.java
但是我不想 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();
}
这显然不起作用,因为我只是检查 f
是否不存在于 src 目录中,它当然存在,因为那是我从那里拉出来的。
我真的很想说if(Files.notExists(f) in target directory)
但我不确定这是否可行。
那么这是合适的方法吗?有没有更好的办法?谢谢
一种方法是为目标文件创建一个 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()));
}
所以我似乎无法找到一种合适的方法来将文件从一个目录复制到另一个目录而不覆盖同名文件。我见过的所有现有 java 方法都会覆盖现有文件 (FileUtils) 或抛出异常 (Files nio)
例如,如果我有一个像这样的文件结构:
├───srcDir
│ ├───this.txt
│ ├───hello.txt
│ ├───main.java
├───destDir
│ ├───this.txt
我想复制 hello.txt
和 main.java
但是我不想 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();
}
这显然不起作用,因为我只是检查 f
是否不存在于 src 目录中,它当然存在,因为那是我从那里拉出来的。
我真的很想说if(Files.notExists(f) in target directory)
但我不确定这是否可行。
那么这是合适的方法吗?有没有更好的办法?谢谢
一种方法是为目标文件创建一个 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()));
}