Here you can find the source of copyDirectory(File srcDir, File dstDir)
Parameter | Description |
---|---|
srcDir | source directory |
dstDir | destination directory |
Parameter | Description |
---|---|
IOException | throws when fail to create the directory structure when copying files |
public static void copyDirectory(File srcDir, File dstDir) throws IOException
//package com.java2s; /*//from w w w . j a va2 s.c o m * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * 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. */ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class Main { /** * Copies all files under srcDir to dstDir. If dstDir does not exist, it will be created. * * @param srcDir source directory * @param dstDir destination directory * @throws IOException throws when fail to create the directory structure when copying files */ public static void copyDirectory(File srcDir, File dstDir) throws IOException { if (srcDir.isDirectory()) { if (!dstDir.exists()) { if (!dstDir.mkdirs()) { throw new IOException("Failed to create directory " + dstDir.getAbsolutePath()); } } String[] children = srcDir.list(); if (children != null) { for (String child : children) { copyDirectory(new File(srcDir, child), new File(dstDir, child)); } } } else { copy(srcDir, dstDir); } } /** * Copies src file to dst file. If the dst file does not exist, it is created. * * @param src source file * @param dst destination file * @throws IOException throws when fail to copy a given file */ public static void copy(File src, File dst) throws IOException { if (dst.getParentFile() != null && !dst.getParentFile().exists()) { if (!dst.getParentFile().mkdirs()) { throw new IOException("Failed to create " + dst.getAbsolutePath()); } } try (InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst)) { // Transfer bytes from in to out byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } } }