Src folder C:\temp
Dest folder C:\temp1
temp has one file (sample.csv)and temp1 folder is empty
I need to copy sample.csv to temp1
Note: I cannot specify sample.csv anywhere in code as this name is dynamic.
Path temp = Files.move(paths.get(src),patha.get(dest)).
This is working only if I give dummy file inside dest directory.
C:\temp1\dummy.csv (i want to specify only C:\temp1 and src folder should go inside temp1)
If you want to copy files from one directory to another one using plain java.nio
, you could make use of a DirectoryStream
.
Here's some example:
public static void main(String[] args) throws Exception {
// define source and destination directories
Path sourceDir = Paths.get("C:\\temp");
Path destinationDir = Paths.get("C:\\temp1");
// check if those paths are valid directories
if (Files.isDirectory(sourceDir, LinkOption.NOFOLLOW_LINKS)
&& Files.isDirectory(destinationDir, LinkOption.NOFOLLOW_LINKS)) {
// if they are, stream the content of the source directory
try (DirectoryStream<Path> ds = Files.newDirectoryStream(sourceDir)) {
// handle each file in that stream
for (Path fso : ds) {
/*
* copy it to the destination,
* that means resolving the file name to the destination directory
*/
Files.move(fso, destinationDir.resolve(fso.getFileName().toString()));
}
}
}
}
You can add more checks, like checking if the directories are readable and actually exist. I just put the check for a directory here in order to show the possibilities of the Files
class.
Apache commons-io library has a FileUtils.copyDirectory()
method. It copies all files from source dir and its subfolders to dest dir, creating dest dir if necessary.
If you are using Gradle, add this to your dependencies section to add this library to your project:
implementation 'commons-io:commons-io:2.11.0'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.