Java Recursive Copy recursiveCopy(File sourceFile, File targetLocation)

Here you can find the source of recursiveCopy(File sourceFile, File targetLocation)

Description

recursive Copy

License

Open Source License

Declaration

private static void recursiveCopy(File sourceFile, File targetLocation) throws IOException 

Method Source Code


//package com.java2s;
/*/*  w  w  w  . j ava  2  s.  c o  m*/
 * Copyright: (c) 2004-2010 Mayo Foundation for Medical Education and 
 * Research (MFMER). All rights reserved. MAYO, MAYO CLINIC, and the
 * triple-shield Mayo logo are trademarks and service marks of MFMER.
 *
 * Except as contained in the copyright notice above, or as used to identify 
 * MFMER as the author of this software, the trade names, trademarks, service
 * marks, or product names of the copyright holder shall not be used in
 * advertising, promotion or otherwise in connection with this software without
 * prior written authorization of the copyright holder.
 * 
 * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html
 * 
 */

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 {
    private static void recursiveCopy(File sourceFile, File targetLocation) throws IOException {
        if (sourceFile.isFile()) {
            copyFile(sourceFile, new File(targetLocation, sourceFile.getName()));
            return;
        }
        // source file must be a directory

        File targetFolder = new File(targetLocation, sourceFile.getName());
        targetFolder.mkdir();

        File[] subFiles = sourceFile.listFiles();
        for (int i = 0; i < subFiles.length; i++) {
            recursiveCopy(subFiles[i], targetFolder);
        }
    }

    private static void copyFile(File sourceFile, File targetFile) throws IOException {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        bis = new BufferedInputStream(new FileInputStream(sourceFile));
        bos = new BufferedOutputStream(new FileOutputStream(targetFile));

        byte[] buffer = new byte[2048];
        while (true) {
            int bytes_read = 0;

            bytes_read = bis.read(buffer);

            if (bytes_read == -1) {
                break;
            }
            bos.write(buffer, 0, bytes_read);
        }

        bis.close();
        bos.close();

        targetFile.setLastModified(sourceFile.lastModified());
    }
}

Related

  1. recursiveCopy(File copyFromDir, File copyToDir, boolean overwrite)
  2. recursiveCopy(File src, File dest)
  3. recursiveCopyDir(File source, File destination)
  4. recursiveCopyFile(File srcDir, File destDir)