[英]How to move all files from source directory to destination directory, keeping existing files in destination directory, using Java NIO?
I am using Java 8 in Windows, I am trying to achieve one simple thing.我在 Windows 中使用 Java 8,我试图实现一件简单的事情。 Say I have a
source
directory and a destination
directory.假设我有一个
source
目录和一个destination
目录。 I am trying to move files from source to destination in a daily basis.我正在尝试每天将文件从源移动到目标。 Below is a simple java code, using NIO;
下面是一个简单的 java 代码,使用 NIO;
Path sourcePath = Paths.get("C:\\source");
Path destinationPath = Paths.get("C:\\destination");
try {
Files.move(sourcePath, destinationPath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
In the first run, this will work fine, because the destination is empty.在第一次运行中,这将正常工作,因为目标是空的。 On the second run, or if the destination is not empty, NIO will throw an exception;
在第二次运行时,或者如果目的地不为空,NIO 将抛出异常;
java.nio.file.DirectoryNotEmptyException: C:\destination
at sun.nio.fs.WindowsFileCopy.move(WindowsFileCopy.java:373)
at sun.nio.fs.WindowsFileSystemProvider.move(WindowsFileSystemProvider.java:287)
at java.nio.file.Files.move(Files.java:1395)
at instacopy.Test.main(Test.java:14)
What I am trying to achieve is;我想要实现的是;
Is this possible?这可能吗? If yes, how can I do this?
如果是,我该怎么做?
first of all:首先:
it would be a good idea to just test if folder is empty.最好只测试文件夹是否为空。
Anyway getting to the point in order to overwrite files in the dest: The best option IMO is to use apache commons.io FileUtils :无论如何,为了覆盖dest中的文件:最好的选择IMO是使用apache commons.io FileUtils :
FileUtils.copyDirectory(srcDir, destDir);
then delete files in the source dir然后删除源目录中的文件
FileUtils.copyDirectory desc: Copies a whole directory to a new location preserving the file dates. FileUtils.copyDirectory desc:将整个目录复制到保留文件日期的新位置。
This method copies the specified directory and all its childdirectories and files to the specified destination.The destination is the new location and name of the directory.此方法将指定目录及其所有子目录和文件复制到指定目标。目标是目录的新位置和名称。
The destination directory is created if it does not exist.If the destination directory did exist, then this method mergesthe source with the destination, with the source taking precedence.如果目标目录不存在,则创建目标目录。如果目标目录确实存在,则此方法将源与目标合并,源优先。
Another option using java nio - you would need to walk through the files and foreach file copy and overwrite使用 java nio 的另一个选项- 您需要遍历文件并 foreach 文件复制和覆盖
Paths target;
try (Stream<Path> paths = Files.walk(sourcePath)) {
paths.forEach((srcPath)->{Files.copy(srcPath, target, StandardCopyOption.REPLACE_EXISTING);});
} catch (IOException e) {
e.printStackTrace();
}
then delete files in the source dir然后删除源目录中的文件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.