Here you can find the source of copyDirectory(File sourceLocation, File targetLocation)
Parameter | Description |
---|---|
sourceLocation | the original directory. |
targetLocation | the destination. |
Parameter | Description |
---|---|
IOException | if the file access fails. |
public static void copyDirectory(File sourceLocation, File targetLocation) throws IOException
//package com.java2s; /** The FileUtils class contains methods for file and directory handling, which comprises reading a file, copying or deleting a directory as well as things like that./*from w w w. j ava 2 s .c om*/ <pre> This file is part of FidoCadJ. FidoCadJ is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. FidoCadJ 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 General Public License for more details. You should have received a copy of the GNU General Public License along with FidoCadJ. If not, see <http://www.gnu.org/licenses/>. Copyright 2008-2015 by Davide Bucci </pre> */ import java.io.*; public class Main { /** Copy a directory recursively. http://subversivebytes.wordpress.com/2012/11/05/java-copy-directory- recursive-delete/ @param sourceLocation the original directory. @param targetLocation the destination. @throws IOException if the file access fails. */ public static void copyDirectory(File sourceLocation, File targetLocation) throws IOException { if (sourceLocation.isDirectory()) { if (!targetLocation.exists() && !targetLocation.mkdir()) { throw new IOException("Can not create temp. directory."); } // Process all the elements of the directory. String[] children = sourceLocation.list(); for (int i = 0; i < children.length; ++i) { copyDirectory(new File(sourceLocation, children[i]), new File(targetLocation, children[i])); } } else { copyFile(sourceLocation, targetLocation); } } /** Copy a file from a location to another one. @param sourceLocation origin of the file to copy. @param targetLocation destination of the file to copy. @throws IOException if the file access fails. */ public static void copyFile(File sourceLocation, File targetLocation) throws IOException { if (sourceLocation.isDirectory()) return; InputStream in = null; OutputStream out = null; // The copy is made by bunch of 1024 bytes. // I wander whether better OS copy funcions exist. try { in = new FileInputStream(sourceLocation); out = new FileOutputStream(targetLocation); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } } finally { if (out != null) out.close(); if (in != null) in.close(); } } }