Java File Copy nio copy(File srcFile, File dstFile)

Here you can find the source of copy(File srcFile, File dstFile)

Description

copy

License

Open Source License

Declaration

public static void copy(File srcFile, File dstFile) throws IOException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2008 The University of York.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * //from  w w w. java2  s. c om
 * Contributors:
 *     Dimitrios Kolovos - initial API and implementation
 ******************************************************************************/

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 copy(File srcFile, File dstFile) throws IOException {
        if (srcFile.isDirectory()) {
            dstFile.mkdir();
            for (File entry : srcFile.listFiles()) {
                copy(entry, new File(dstFile, entry.getName()));
            }
        } else {
            // Based on the second answer in http://stackoverflow.com/questions/106770.
            FileInputStream isSrc = null;
            FileOutputStream osDst = null;
            FileChannel chSrc = null;
            FileChannel chDst = null;
            try {
                isSrc = new FileInputStream(srcFile);
                osDst = new FileOutputStream(dstFile);
                chSrc = isSrc.getChannel();
                chDst = osDst.getChannel();
                final long srcBytes = srcFile.length();
                long transferred = 0;
                while (transferred < srcBytes) {
                    transferred += chDst.transferFrom(chSrc, transferred, srcBytes);
                    chDst.position(transferred);
                }
            } finally {
                if (chDst != null) {
                    chDst.close();
                } else if (osDst != null) {
                    osDst.close();
                }

                if (chSrc != null) {
                    chSrc.close();
                } else if (isSrc != null) {
                    isSrc.close();
                }
            }
        }
    }
}

Related

  1. copy(File src, File folder)
  2. copy(File src, File target)
  3. copy(File src, File target)
  4. copy(File srcDir, File relSrcFile, File destDir, File relDestFile)
  5. copy(File srcfile, File destfile)
  6. copy(File srcFileOrDir, File targetFileOrDir)
  7. copy(File toFile, File fromFile)
  8. copyFile(File f1, File f2)
  9. copyFile(File source, File dest, boolean visibleFilesOnly)