Source Code : Copying a directory using the SimpleFileVisitor class
Java Is Open Source Programming Language You Can Download From Java and Java Libraries From http://www.oracle.com.
Click Here to download
We provide this code related to title for you to solve your developing problem easily. Libraries which is import in this program you can download from http://www.oracle.com.
Click Here or search from google with Libraries Name you get jar file related it
Copying a directory using the SimpleFileVisitor class
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.FileVisitOption;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.EnumSet;
public class Test {
public static void main(String[] args) {
try {
Path source = Paths.get("/home");
Path target = Paths.get("/backup");
Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS),
Integer.MAX_VALUE, new CopyDirectory(source, target));
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
class CopyDirectory extends SimpleFileVisitor<Path> {
private Path source;
private Path target;
public CopyDirectory(Path source, Path target) {
this.source = source;
this.target = target;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes)
throws IOException {
System.out.println("Copying " + source.relativize(file));
Files.copy(file, target.resolve(source.relativize(file)));
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult preVisitDirectory(Path directory,
BasicFileAttributes attributes) throws IOException {
Path targetDirectory = target.resolve(source.relativize(directory));
try {
System.out.println("Copying " + source.relativize(directory));
Files.copy(directory, targetDirectory);
} catch (FileAlreadyExistsException e) {
if (!Files.isDirectory(targetDirectory)) {
throw e;
}
}
return FileVisitResult.CONTINUE;
}
}
Thank with us