Java Directory Copy nio copyDirectory(final File sourceFile, final File targetDir)

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

Description

copy Directory

License

Mozilla Public License

Declaration

public static void copyDirectory(final File sourceFile,
            final File targetDir) throws IOException 

Method Source Code

//package com.java2s;
/**//w ww.j  a v a  2 s.  com
 * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
 *
 * If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;

public class Main {
    public static void copyDirectory(final File sourceFile,
            final File targetDir) throws IOException {
        if (!sourceFile.isDirectory()) {
            throw new IllegalStateException(
                    "Source file should be a directory.");
        }

        if (!targetDir.getParentFile().exists()) {
            if (!targetDir.getParentFile().mkdirs()) {
                throw new IOException("Could not create "
                        + targetDir.getParentFile().getAbsolutePath());
            }
        }

        if (Files.isSymbolicLink(sourceFile.toPath())) {
            Path linkTarget = Files.readSymbolicLink(sourceFile.toPath());
            Files.createSymbolicLink(targetDir.toPath(), linkTarget);
            return;
        }

        if (!targetDir.exists()) {
            if (!targetDir.mkdir()) {
                throw new IOException("Could not create "
                        + targetDir.getAbsolutePath());
            }
        }

        for (String file : sourceFile.list()) {
            if (file.startsWith(".attach_pid")) {
                continue;
            }
            File sf = new File(sourceFile, file);
            File newFile = new File(targetDir, file);
            if (sf.isDirectory()) {
                copyDirectory(sf, newFile);
            } else {
                Files.copy(sf.toPath(), newFile.toPath(),
                        LinkOption.NOFOLLOW_LINKS);
            }
        }
    }
}

Related

  1. copyDirectory(File src, File dest)
  2. copyDirectory(File src, File target)
  3. copyDirectory(File srcDir, File destDir)
  4. copyDirectory(File srcDir, File destDir, boolean preserveFileDate)
  5. copyDirectory(final File source, final File destination)
  6. copyDirectory(final File srcDir, final File destDir)
  7. copyDirectory(final Path source, final Path destination)
  8. copyDirectory(final Path source, final Path destination, List excludes)
  9. copyDirectory(Path source, ArrayList targets)