Reputation: 3092
Can anyone help me for a Java code which copy or move one folder as it is into another folder.
For example:
I have a folder named temp
, inside temp
I have a folder in-temp
.
I want that my temp
folder should be copied or moved into a new folder named new temp
, but by using Java code.
I got an example code by searching on Google which copies the sub-directories and files of a folder into a new folder, but as I said I need to move a folder with it's sub-folder into a new folder.
Help me to resolve this.
Thank you.
Upvotes: 4
Views: 2574
Reputation: 4667
For most cases, specifically when source and target are on the same filesystem, respectively drive, the standard java.nio Files.move(Path source, Path target, CopyOption... options)
command (available since Java 7) does exactly what you need. However, the command will fail in some cases, so you'd have to resort/fallback to to copy & delete the directory recursively (this pattern is also found in commons-io's FileUtils.moveDirectory
).
This is a helper method that i just recently implemented in a Spring Boot project (as part of an effort to remove commons-io from the project's stack, using native & existing spring methods):
public static Path move(Path source, Path target) throws IOException {
if (Files.exists(target)) {
throw new FileAlreadyExistsException(String.format("Destination '%s' already exists", target));
}
try {
return Files.move(source, target);
} catch (IOException ignored) {
// you may want some logging here, or just ignore the exception
}
FileSystemUtils.copyRecursively(source, target);
FileSystemUtils.deleteRecursively(source);
return target;
}
The two FileSystemUtils
methods are part of the spring framework, but if you don't have a spring-based project… their implementations are pretty straightforward :)
I am documenting them here below, the following is just a copy from the original source code from Github.
/**
* Recursively copy the contents of the {@code src} file/directory
* to the {@code dest} file/directory.
* @param src the source directory
* @param dest the destination directory
* @throws IOException in the case of I/O errors
* @since 5.0
*/
public static void copyRecursively(Path src, Path dest) throws IOException {
Assert.notNull(src, "Source Path must not be null");
Assert.notNull(dest, "Destination Path must not be null");
BasicFileAttributes srcAttr = Files.readAttributes(src, BasicFileAttributes.class);
if (srcAttr.isDirectory()) {
Files.walkFileTree(src, EnumSet.of(FOLLOW_LINKS), Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
Files.createDirectories(dest.resolve(src.relativize(dir)));
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.copy(file, dest.resolve(src.relativize(file)), StandardCopyOption.REPLACE_EXISTING);
return FileVisitResult.CONTINUE;
}
});
}
else if (srcAttr.isRegularFile()) {
Files.copy(src, dest);
}
else {
throw new IllegalArgumentException("Source File must denote a directory or file");
}
}
/**
* Delete the supplied {@link Path} — for directories,
* recursively delete any nested directories or files as well.
* @param root the root {@code Path} to delete
* @return {@code true} if the {@code Path} existed and was deleted,
* or {@code false} if it did not exist
* @throws IOException in the case of I/O errors
* @since 5.0
*/
public static boolean deleteRecursively(@Nullable Path root) throws IOException {
if (root == null) {
return false;
}
if (!Files.exists(root)) {
return false;
}
Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
return true;
}
This code works great – if you're not sure what you're looking at here, then you'll want to develop a basic understanding of the File Visitor API – which is a really powerful pattern to efficiently traverse directories for a multitude of purposes (i.e. get folder size, list files, etc.).
Upvotes: 0
Reputation: 10154
You can use apache-commons-io:
org.apache.commons.io.FileUtils.copyDirectory(File, File)
Upvotes: 11