Java Copy Directory copyDirectory(File srcDir, File dstDir)

Here you can find the source of copyDirectory(File srcDir, File dstDir)

Description

copy Directory

License

Open Source License

Declaration

public static void copyDirectory(File srcDir, File dstDir) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;
import java.io.FileOutputStream;

import java.io.IOException;

public class Main {
    public static void copyDirectory(File srcDir, File dstDir) throws IOException {
        if (srcDir.isDirectory()) {
            if (!dstDir.exists()) {
                dstDir.mkdir();//from w  w  w .j a v  a2 s .  co m
            }

            String[] children = srcDir.list();
            for (int i = 0; i < children.length; i++) {
                copyDirectory(new File(srcDir, children[i]), new File(dstDir, children[i]));
            }
        } else {
            copyFile(srcDir, dstDir);
        }
    }

    public static void copyFile(File in, File out) throws IOException {
        File inCannon = in.getCanonicalFile();
        File outCannon = out.getCanonicalFile();
        // avoids copying a file to itself
        if (inCannon.equals(outCannon)) {
            return;
        }
        // ensure the output file location exists
        outCannon.getParentFile().mkdirs();

        BufferedInputStream fis = new BufferedInputStream(new FileInputStream(inCannon));
        BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(outCannon));

        // a temporary buffer to read into
        byte[] tmpBuffer = new byte[8192];
        int len = 0;
        while ((len = fis.read(tmpBuffer)) != -1) {
            // add the temp data to the output
            fos.write(tmpBuffer, 0, len);
        }
        // close the input stream
        fis.close();
        // close the output stream
        fos.flush();
        fos.close();
    }

    /**
     * Like Object.equals, but if o1 == null && o2 == null, returns true
     * 
     * @param o1
     * @param o2
     * @return
     */
    public static boolean equals(Object o1, Object o2) {
        if (o1 == null) {
            return o2 == null;
        }
        return o1.equals(o2);
    }
}

Related

  1. copyDirectory(File src, File dest, boolean force)
  2. copyDirectory(File src, File dst)
  3. copyDirectory(File srcDir, File destDir)
  4. copyDirectory(File srcDir, File dstDir)
  5. copyDirectory(File srcDir, File dstDir)
  6. copyDirectory(File srcDir, File dstDir)
  7. copyDirectory(File srcDir, File dstDir)
  8. copyDirectory(File srcDir, File dstDir)
  9. copyDirectory(File srcFile, File destFile)