Java Folder Copy nio copyFolder(File sourceFolder, File destinationFolder)

Here you can find the source of copyFolder(File sourceFolder, File destinationFolder)

Description

copy Folder

License

Open Source License

Declaration

public static void copyFolder(File sourceFolder, File destinationFolder) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.*;

import java.nio.channels.FileChannel;

public class Main {
    public static void copyFolder(File sourceFolder, File destinationFolder) {
        copyFolder(sourceFolder, destinationFolder, true);
    }/*from   w ww . ja va2s.com*/

    public static void copyFolder(File sourceFolder, File destinationFolder, boolean overwrite) {
        if (sourceFolder.isDirectory()) {
            if (!destinationFolder.exists()) {
                destinationFolder.mkdirs();
            }
            String files[] = sourceFolder.list();
            for (String file : files) {
                File srcFile = new File(sourceFolder, file);
                File destFile = new File(destinationFolder, file);
                copyFolder(srcFile, destFile);
            }
        } else {
            copyFile(sourceFolder, destinationFolder, overwrite);
        }
    }

    public static void copyFile(File sourceFile, File destinationFile) {
        copyFile(sourceFile, destinationFile, true);
    }

    public static void copyFile(File sourceFile, File destinationFile, boolean overwrite) {
        try {
            if (sourceFile.exists()) {
                if (!overwrite && destinationFile.exists()) {
                    System.out.println("Destination file exists\n" + sourceFile.getAbsolutePath());
                    return;
                }
                if (!destinationFile.exists()) {
                    destinationFile.createNewFile();
                }
                FileChannel sourceStream = null, destinationStream = null;
                try {
                    sourceStream = new FileInputStream(sourceFile).getChannel();
                    destinationStream = new FileOutputStream(destinationFile).getChannel();
                    destinationStream.transferFrom(sourceStream, 0, sourceStream.size());
                } finally {
                    if (sourceStream != null) {
                        sourceStream.close();
                    }
                    if (destinationStream != null) {
                        destinationStream.close();
                    }
                }
            } else {
                System.out.println("Source file does not exist\n" + sourceFile.getAbsolutePath());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Related

  1. copyFolder(File sourceFolder, File destinationFolder)
  2. copyFolder(File sourceFolder, File destinationFolder, List blacklist)
  3. copyFolder(File src, File dest)
  4. copyFolder(File src, File dest)