Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package duplicatedir;
- import java.io.File;
- import java.io.IOException;
- import java.io.RandomAccessFile;
- import java.nio.channels.FileChannel;
- import java.util.ArrayList;
- import java.util.Scanner;
- public class DuplicateDir {
- public static void main(String[] args) {
- Scanner kb = new Scanner(System.in);
- System.out.println("Source Path:");
- String src = kb.nextLine();
- System.out.println("================================================");
- System.out.println("Destination Path:");
- try {
- String des = kb.nextLine();
- System.out.println("================================================");
- File Dir1 = new File(src);
- File Dir2 = new File(des);
- if (Dir1.equals(Dir2)) {
- System.out.println("Error: Source and Destination Match");
- } else {
- CrawlerCopy(Dir1, Dir2);
- System.out.println("COMPLETED");
- }
- } catch (Exception ex) {
- System.out.println(ex.getMessage());
- }
- }
- private static void CrawlerCopy(File source, File destination) throws Exception {
- if (source.exists()) {
- if (source.isDirectory()) {
- if (!destination.exists()) {
- System.out.println("Making Dir:");
- System.out.println(" Path: " + destination.getAbsolutePath());
- destination.mkdir();
- System.out.println("DONE");
- System.out.println("================================================");
- }
- ArrayList<File> folders = new ArrayList<>();
- String[] stuff = source.list();
- for (String s : stuff) {
- File crnt = new File(source.getAbsolutePath() + "\\" + s);
- if (crnt.isFile()) {
- copyFile(crnt, new File(destination.getAbsolutePath() + "\\" + crnt.getName()));
- }
- if (crnt.isDirectory()) {
- folders.add(crnt);
- }
- }
- for (File f : folders) {
- CrawlerCopy(f, new File(destination.getAbsolutePath() + "\\" + f.getName()));
- }
- } else if (source.isFile()) {
- copyFile(source, destination);
- }
- }
- }
- public static void copyFile(File sourceFile, File destFile) throws IOException {
- if (!destFile.exists()) {
- destFile.createNewFile();
- }
- FileChannel source = null;
- FileChannel destination = null;
- try {
- source = new RandomAccessFile(sourceFile, "rw").getChannel();
- destination = new RandomAccessFile(destFile, "rw").getChannel();
- long position = 0;
- long count = source.size();
- System.out.println("Copying:");
- System.out.println(" From: " + sourceFile.getAbsolutePath());
- System.out.println(" To: " + destFile.getAbsolutePath());
- source.transferTo(position, count, destination);
- System.out.println("DONE");
- } catch (IOException e) {
- System.out.println("FAILED");
- } finally {
- if (source != null) {
- source.close();
- }
- if (destination != null) {
- destination.close();
- }
- System.out.println("================================================");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment