Here you can find the source of copyDirectory(File sourceDir, File destinationDir)
Parameter | Description |
---|---|
sourceDir | The source directory. |
destinationDir | The destination directory. |
public static void copyDirectory(File sourceDir, File destinationDir)
//package com.java2s; /*/*from www .j a v a2 s . c om*/ * Copyright 2012 BMW Car IT GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.channels.FileChannel; public class Main { /** * Copies the contents of one directory into the other. Will not change modified flags of files. * * @param sourceDir * The source directory. * @param destinationDir * The destination directory. */ public static void copyDirectory(File sourceDir, File destinationDir) { if (sourceDir == null || !sourceDir.exists() || destinationDir == null) { return; } destinationDir.mkdirs(); File[] files = sourceDir.listFiles(); if (files == null) { files = new File[0]; } for (File sourceFile : files) { if (sourceFile.isDirectory()) { // recursive copy of directories File newDestSubDir = new File(destinationDir, sourceFile.getName()); newDestSubDir.mkdirs(); newDestSubDir.setLastModified(sourceFile.lastModified()); copyDirectory(sourceFile, newDestSubDir); } else { // copy file File destFile = new File(destinationDir, sourceFile.getName()); copyFile(sourceFile, destFile); destFile.setLastModified(sourceFile.lastModified()); // don't change modified flag! } } } private static void copyFile(File sourceFile, File destFile) { try { FileInputStream source = new FileInputStream(sourceFile); FileOutputStream destination = new FileOutputStream(destFile); FileChannel sourceFileChannel = source.getChannel(); FileChannel destinationFileChannel = destination.getChannel(); sourceFileChannel.transferTo(0, sourceFileChannel.size(), destinationFileChannel); source.close(); destination.close(); } catch (Exception ex) { throw new IllegalArgumentException(ex); } } }