Java Directory Copy copyDirectory(File source, File destination)

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

Description

Copying recursively a directory to another.

License

Open Source License

Parameter

Parameter Description
source the source directory (or file to copy)
destination the destination directory.

Return

true if the copy was successfull, false if the copy was unsuccessfull

Declaration

public static boolean copyDirectory(File source, File destination) 

Method Source Code


//package com.java2s;
/*//from  w w  w. ja v  a2 s  .  c om
  This file is part of JOrigin Common Library.
    
JOrigin Common 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.
    
JOrigin Common 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 JOrigin Common.  If not, see <http://www.gnu.org/licenses/>.
    
*/

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;

public class Main {
    /**
     * Copying recursively a directory to another. If the destination directory does not exist, it is created.
     * @param source the source directory (or file to copy)
     * @param destination the destination directory.
     * @return <code>true</code> if the copy was successfull, <code>false</code> if the copy was unsuccessfull
     */
    public static boolean copyDirectory(File source, File destination) {
        boolean result = true;
        // Premiere verification: le source existe t'il
        if (!source.exists()) {
            return false;
        }
        // Cree le repertoire de destination s'il n'existe pas
        if ((destination.mkdirs() == false) && (!destination.isDirectory())) {
            return false;
        }
        // Liste les fichiers du repertoire
        File[] files = source.listFiles();
        // Parcours de la liste de fichiers et copie recursive
        for (int i = 0; i < files.length; i++) {
            // La destination change en fonction du fichier copie
            File newDestination = new File(destination.getPath() + File.separator + files[i].getName());
            if (files[i].isDirectory()) {
                result &= copyDirectory(files[i], newDestination);
            } else {
                result &= copy(files[i], newDestination);
            }
        }
        // en cas de probleme, toute la copie doit etre annulee
        //if (result == false)
        //  deleteDirectory(destination);
        return result;
    }

    /**
     * List recursively a directory and its sub-directories.
     * @param source the source directory (or file to copy).
     * @param filter a {@link java.io.FileFilter filter} used for accepting files within the list.
     * @return the list of files presents in the directory.
     */
    public static ArrayList<File> listFiles(File source, FileFilter filter) {
        ArrayList<File> list = null;
        // Premiere verification: le source existe t'il
        if (!source.exists()) {
            return null;
        } else {
            list = new ArrayList<File>();
        }
        // Liste les fichiers du repertoire
        File[] files = source.listFiles();
        // Parcours de la liste de fichiers et copie recursive
        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                list.addAll(listFiles(files[i], filter));
            } else {
                if ((filter == null) || (filter.accept(files[i]))) {
                    list.add(files[i]);
                }
            }
        }
        return list;
    }

    /**
     * Simple copy of a source file to a destination file
     * @param source the path of the source file
     * @param destination the path of the destination file
     * @return <code>true</code> if the copy was successfull and <code>false</code> if not
     */
    public static boolean copy(File source, File destination) {
        boolean result = false;
        /* Declaration des flux */
        java.io.FileInputStream sourceFile = null;
        java.io.FileOutputStream destinationFile = null;
        try {
            // Cretion du fichier
            destination.createNewFile();
            // Ouverture des flux
            sourceFile = new java.io.FileInputStream(source);
            destinationFile = new java.io.FileOutputStream(destination);
            // Lecture par segment de 0.5M
            byte buffer[] = new byte[1024];
            int nbLecture;
            while ((nbLecture = sourceFile.read(buffer)) != -1) {
                destinationFile.write(buffer, 0, nbLecture);
            }
            // Copie reussie
            result = true;
        } catch (java.io.FileNotFoundException f) {
            System.err.println(f);
            result = false;
        } catch (java.io.IOException e) {
            System.err.println(e);
            result = false;
        } finally {
            /* Quoi qu'il arrive, on ferme les flux */
            try {
                sourceFile.close();
            } catch (Exception e) {
            }
            try {
                destinationFile.close();
            } catch (Exception e) {
            }
        }
        return (result);
    }
}

Related

  1. copyDirectory(File inDir, File outDir)
  2. copyDirectory(File inDir, File outDir)
  3. copyDirectory(File inputFolder, File outputFolder)
  4. copyDirectory(File source, File destination)
  5. copyDirectory(File source, File destination)
  6. copyDirectory(File source, File destination)
  7. copyDirectory(File source, File destination, boolean overwrite)
  8. copyDirectory(File source, File destination, String endWith)
  9. copyDirectory(File source, File target)