Here you can find the source of copyRec(File src, File dst)
Parameter | Description |
---|---|
src | source. |
dst | destination. |
Parameter | Description |
---|
public static void copyRec(File src, File dst) throws IOException
//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 w w .j a v a2 s. co m * Copies a directory or a file from source to destination. * * @param src source. * @param dst destination. * * @throws java.io.IOException in case of I/O error. */ public static void copyRec(File src, File dst) throws IOException { if (src == null || dst == null) return; if (dst.isFile()) return; if (src.isFile()) { // Copy file copyFileToDir(src, dst); } else { // Construct destination directory file String name = src.getName(); File newDst = new File(dst, name); if (!newDst.exists()) { // Create the destination directory if it doesn't exist yet newDst.mkdir(); } else if (newDst.isFile()) { throw new IOException("There's a file " + newDst.getName() + " in place of directory"); } // Copy files and directories from the source to a new destination recursively for (File file : src.listFiles()) copyRec(file, newDst); } } /** * 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(); } } }