Java Copy Directory copyDirectory(String sourceDir, String targetDir)

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

Description

copy Directory

License

Apache License

Declaration

public static void copyDirectory(String sourceDir, String targetDir) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.*;

public class Main {
    public static void copyDirectory(String sourceDir, String targetDir) {
        File sourceFolder = new File(sourceDir);
        if (sourceFolder.exists()) {
            File targetFolder = new File(targetDir);
            if (!targetFolder.exists()) {
                targetFolder.mkdirs();/*from   w  w w.  j a  va  2s  .  c  o m*/
            }
            File[] files = sourceFolder.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (files[i].isFile()) {
                    File sourceFile = files[i];
                    File targetFile = new File(
                            new File(targetDir).getAbsoluteFile() + File.separator + files[i].getName());
                    copy(sourceFile, targetFile);
                } else if (files[i].isDirectory()) {
                    String dir1 = sourceDir + "/" + files[i].getName();
                    String dir2 = targetDir + "/" + files[i].getName();
                    copyDirectory(dir1, dir2);
                }
            }
        }
    }

    public static void copy(File src, File des) {

        try {
            int BUFFER_SIZE = 32 * 1024;
            InputStream in = null;
            OutputStream out = null;
            try {
                in = new FileInputStream(src);
                out = new FileOutputStream(des);
                byte[] buffer = new byte[BUFFER_SIZE];
                int count = 0;
                while ((count = in.read(buffer)) != -1) {
                    out.write(buffer, 0, count);
                }
            } finally {
                if (in != null) {
                    in.close();
                }
                if (null != out) {
                    out.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Related

  1. copyDirectory(File srcPath, File dstPath)
  2. copyDirectory(File srcPath, File dstPath)
  3. copyDirectory(final File sourceDir, final File destDir)
  4. copyDirectory(final File src, final File dest)
  5. copyDirectory(final String sourceDir, final String targetDir)
  6. copyDirectory(String srcDir, String destDir)
  7. copyDirectoryAndOverwriteFilesIfNeeded(File srcDir, File destDir)
  8. copyDirectoryContent(File srcPath, File targetPath)
  9. copyDirectoryContents(File directory, String targetDirName, boolean update)