Java FileChannel Copy copyFileOrDirectory(File source, File destination, boolean flag)

Here you can find the source of copyFileOrDirectory(File source, File destination, boolean flag)

Description

copy File Or Directory

License

Open Source License

Declaration

public static void copyFileOrDirectory(File source, File destination, boolean flag) throws IOException 

Method Source Code


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

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class Main {
    public static void copyFileOrDirectory(File source, File destination, boolean flag) throws IOException {
        //try {/* w  ww.ja  va 2s.c  o  m*/
        if ((destination.isFile()) && (!(source.isFile()))) {
            throw new IOException("Impossible to copy  directory");
        }
        if ((source.isFile()) && (destination.isDirectory())) {
            copy(source, new File(destination.getPath(), source.getName()));
        } else if (source.isFile()) {
            try {
                copy(source, destination);
            } catch (Exception e) {
                System.err.println("cannot copy");
            }
        } else {
            File elementsDestination = new File(destination.getPath(), source.getName());

            if (!elementsDestination.exists()) {
                if (!elementsDestination.mkdir()) {
                    throw new IOException();
                }
            }
            for (String element : source.list()) {
                copyFileOrDirectory(new File(source.getPath(), element), elementsDestination, flag);
            }
        }
        //} catch (Exception e) {
        //    System.err.println("A problem with reading from source file or writing to destination file");
        //}
    }

    public static void copy(File source, File destination) throws IOException {
        try {
            FileChannel sourceChannel = new FileInputStream(source.getPath()).getChannel();
            FileChannel destinationChannel = new FileOutputStream(destination.getPath()).getChannel();
            destinationChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
            sourceChannel.close();
            destinationChannel.close();
        } catch (Exception e) {
            System.err.println("Couldn't close sources or write");
        }
    }
}

Related

  1. copyFileContent(final String sourcePath, final String targetPath)
  2. copyFileIntoProjectFolder(String projectName, File file)
  3. copyFileLocking(File copyFrom, File copyTo)
  4. copyFileNIO(File src, File dest)
  5. copyFileNio(File src, File dst)
  6. copyFiles(File originalFile, File destinationFile)
  7. copyFiles(File source, File dest)
  8. copyFiles(File srcFile, File dstFile, boolean overwrite)
  9. copyFiles(final File fromFile, final File toFile)