Java FileChannel Copy copyFileToDir(File file, File destDir)

Here you can find the source of copyFileToDir(File file, File destDir)

Description

Copies file from it's location to destination dir.

License

Open Source License

Parameter

Parameter Description
file file to copy.
destDir dir.

Exception

Parameter Description

Declaration

public static void copyFileToDir(File file, File destDir) throws IOException 

Method Source Code


//package com.java2s;
// the terms of the GNU General Public License as published by the Free Software Foundation;

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

public class Main {
    /**//from   w  ww . ja  va  2  s .  c  om
     * Copies file from it's location to destination dir.
     *
     * @param file      file to copy.
     * @param destDir   dir.
     *
     * @throws java.io.IOException if I/O error happens.
     */
    public static void copyFileToDir(File file, File destDir) throws IOException {
        String name = file.getName();
        String filename = destDir.getAbsolutePath() + File.separator + name;

        File destFile = new File(filename);
        destFile.createNewFile();

        copyFileToFile(file, destFile);
    }

    /**
     * Copies one file to another.
     *
     * @param source    source file.
     * @param dest      destination file.
     *
     * @throws java.io.IOException if I/O error happens.
     */
    public static void copyFileToFile(File source, File dest) throws IOException {
        FileChannel sourceChannel = null;
        FileChannel targetChannel = null;

        try {
            sourceChannel = new FileInputStream(source).getChannel();
            targetChannel = new FileOutputStream(dest).getChannel();
            sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);
            targetChannel.force(true);
        } finally {
            if (sourceChannel != null)
                sourceChannel.close();
            if (targetChannel != null)
                targetChannel.close();
        }
    }
}

Related

  1. copyFileOrDirectory(File source, File destination, boolean flag)
  2. copyFiles(File originalFile, File destinationFile)
  3. copyFiles(File source, File dest)
  4. copyFiles(File srcFile, File dstFile, boolean overwrite)
  5. copyFiles(final File fromFile, final File toFile)
  6. copyFileToDirectory(String fileFrom, String destinationDirectory)
  7. copyFileToFolder(final String resultFile, final String targetPath)
  8. copyFileToStream(File in, OutputStream out)
  9. copyFileUsingChannel(File source, File dest)