Java Directory Copy nio copyDirectiory(String sourceDir, String targetDir)

Here you can find the source of copyDirectiory(String sourceDir, String targetDir)

Description

copy Directiory

License

Open Source License

Declaration

public static void copyDirectiory(String sourceDir, String targetDir) throws IOException 

Method Source Code

//package com.java2s;
/**/*from w  ww .  ja  va 2 s.c  o m*/
 * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 */

import java.io.File;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;

public class Main {
    public static void copyDirectiory(String sourceDir, String targetDir) throws IOException {
        (new File(targetDir)).mkdirs();

        File[] file = (new File(sourceDir)).listFiles();

        for (int i = 0; i < file.length; i++) {
            if (file[i].isFile()) {
                File sourceFile = file[i];
                File targetFile = new File(
                        new File(targetDir).getAbsolutePath() + File.separator + file[i].getName());

                copyFile(sourceFile, targetFile);
            }

            if (file[i].isDirectory()) {
                String dir1 = sourceDir + "/" + file[i].getName();
                String dir2 = targetDir + "/" + file[i].getName();

                copyDirectiory(dir1, dir2);
            }
        }
    }

    public static void copyFile(File src, File dest) {
        if ((src == null) || !src.exists() || (dest == null) || dest.isDirectory()) {
            return;
        }

        byte[] buf = new byte[4096];

        try (InputStream in = Files.newInputStream(src.toPath());
                OutputStream out = Files.newOutputStream(dest.toPath())) {

            int avail = in.read(buf);

            while (avail > 0) {
                out.write(buf, 0, avail);
                avail = in.read(buf);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Related

  1. copyDir(final Path fromPath, final Path toPath)
  2. copyDir(final String src, final String dest)
  3. copyDir(Path from, Path to, IProgressMonitor monitor)
  4. copyDir(String sourceDir, String targetDir)
  5. copyDir(String src, String dst)
  6. copyDirectory(File in, File out)
  7. copyDirectory(File in, File out)
  8. copyDirectory(File source, File dest, CopyOption... options)
  9. copyDirectory(File source, File destination)