Java Directory Copy nio copyDirectory(File sourceDir, File targetDir)

Here you can find the source of copyDirectory(File sourceDir, File targetDir)

Description

copy Directory

License

Apache License

Declaration

public static void copyDirectory(File sourceDir, File targetDir) throws IOException 

Method Source Code


//package com.java2s;
/*-//from  w w  w . ja v a 2s  .c  om
 * ========================LICENSE_START=================================
 * com.geewhiz.pacify.common
 * %%
 * Copyright (C) 2011 - 2017 Sven Oppermann
 * %%
 * 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.
 * =========================LICENSE_END==================================
 */

import java.io.File;

import java.io.IOException;

import java.nio.file.Files;

public class Main {
    public static void copyDirectory(File sourceDir, File targetDir) throws IOException {
        if (sourceDir.isDirectory()) {
            copyDirectoryRecursively(sourceDir.getAbsoluteFile(), targetDir.getAbsoluteFile());
        } else {
            Files.copy(sourceDir.getAbsoluteFile().toPath(), targetDir.getAbsoluteFile().toPath(),
                    java.nio.file.StandardCopyOption.COPY_ATTRIBUTES);
        }
    }

    private static void copyDirectoryRecursively(File source, File target) throws IOException {
        if (!target.exists()) {
            Files.copy(source.toPath(), target.toPath(), java.nio.file.StandardCopyOption.COPY_ATTRIBUTES);
        }

        for (String child : source.list()) {
            copyDirectory(new File(source, child), new File(target, child));
        }
    }
}

Related

  1. copyDirectory(File source, File destination)
  2. copyDirectory(File source, File destination)
  3. copyDirectory(File source, File destination, boolean recursive)
  4. copyDirectory(File source, File target, boolean acceptFileInUseError)
  5. copyDirectory(File sourceDir, File destinationDir)
  6. copyDirectory(File sourceDirectory, File targetDirectory)
  7. copyDirectory(File sourceFile, File destFile)
  8. copyDirectory(File src, File dest)
  9. copyDirectory(File src, File target)