Java FileChannel Copy directoryCopy(URL source, URL destination)

Here you can find the source of directoryCopy(URL source, URL destination)

Description

Copies the contents for source directory to destination directory.

License

Open Source License

Parameter

Parameter Description
source - directory on the file system or jar file
destination - a directory on the file system

Exception

Parameter Description
IllegalArgumentException <ul><li>source or destination is null or not a file</li><li>destination is not a file URL</li></ul>

Declaration

public static void directoryCopy(URL source, URL destination) throws IOException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2013 Red Hat, Inc./*  w  w  w  . j  av a2 s  . co m*/
 * Distributed under license by Red Hat, Inc. All rights reserved.
 * This program is made available under the terms of the
 * Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Red Hat, Inc. - initial API and implementation
 ******************************************************************************/

import java.io.File;
import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;
import java.io.InputStream;

import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;

import java.util.Enumeration;

import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.eclipse.core.runtime.FileLocator;

public class Main {
    /**
     * Copies the contents for source directory to destination directory. 
     * Source can be a directory on the file system or a jar file.
     * Destination is a directory on the files system 
     * 
     * @param source - directory on the file system or jar file
     * @param destination - a directory on the file system
     * @throws IllegalArgumentException 
     *       <ul>
     *          <li>source or destination is null or not a file</li>
     *        <li>destination is not a file URL</li>
     *     </ul>
     */
    public static void directoryCopy(URL source, URL destination) throws IOException {
        checkCanCopy(source, destination);

        source = getFileURL(source);
        destination = getFileURL(destination);
        File dstFile = new File(destination.getFile());
        if (!dstFile.exists() && !dstFile.mkdir()) {
            return;
        }

        if ("file".equals(source.getProtocol())) {
            File srcFile = new File(source.getFile());
            copyFile(srcFile, dstFile);

        } else if ("jar".equals(source.getProtocol())) {
            ZipFile zipFile = getZipFile(source);
            String file = source.getFile();
            int exclamation = file.indexOf('!');
            String jarLocation = file.substring(exclamation + 2); // "/some/path/"
            copyFromZip(zipFile, jarLocation, dstFile);
        }

    }

    private static void checkCanCopy(URL source, URL destination) {
        if (source == null || destination == null)
            throw new IllegalArgumentException("null source or destination value");
        getFileURL(source);
        destination = getFileURL(destination);
        if (!isFile(destination))
            throw new IllegalArgumentException("destination is not a file URL");
    }

    private static URL getFileURL(URL url) {
        try {
            url = FileLocator.resolve(url);
            return FileLocator.toFileURL(url);
        } catch (IOException e) {
            return null;
        }
    }

    private static void copyFile(File source, File target) throws IOException {

        File file = null;
        if (source.isDirectory() && source.exists() && target.isDirectory() && target.exists()) {

            File[] children = source.listFiles();
            for (File child : children) {
                file = target;
                if (child.isDirectory()) {
                    file = new File(target, child.getName());
                    if (!file.exists())
                        file.mkdir();
                }
                copyFile(child, file);
            }
        } else {// source is a file
            if (target.isFile()) {
                file = target;
            } else {
                file = new File(target, source.getName());
            }

            FileChannel out = null;
            FileChannel in = null;
            try {
                if (!file.exists()) {
                    file.createNewFile();
                }

                out = new FileOutputStream(file).getChannel();
                in = new FileInputStream(source).getChannel();
                in.transferTo(0, in.size(), out);
            } catch (IOException e) {
                e.printStackTrace();
                throw e;
            } finally {
                if (out != null)
                    out.close();
                if (in != null)
                    in.close();
            }
        }
    }

    private static ZipFile getZipFile(URL url) {
        if (!"jar".equals(url.getProtocol()))
            return null;
        String file = url.getFile();
        int exclamation = file.indexOf('!');
        if (exclamation < 0)
            return null;
        URL fileUrl = null;
        try {
            fileUrl = new URL(file.substring(0, exclamation));
        } catch (MalformedURLException mue) {
            return null;
        }
        File pluginJar = new File(fileUrl.getFile());
        if (!pluginJar.exists())
            return null;

        try {
            ZipFile zipFile = new ZipFile(pluginJar);
            return zipFile;
        } catch (IOException e) {
            return null;
        }
    }

    private static void copyFromZip(ZipFile zipFile, String locationInBundle, File destination) throws IOException {

        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry zipEntry = entries.nextElement();
            if (zipEntry.getName().startsWith(locationInBundle)) {

                String path = zipEntry.getName().substring(locationInBundle.length());
                File file = new File(destination, path);

                if (!zipEntry.isDirectory()) {
                    createFileFromZipFile(file, zipFile, zipEntry);
                } else {
                    if (!file.exists()) {
                        file.mkdir();
                    }
                }
            }
        }

    }

    private static boolean isFile(URL url) {
        return "file".equals(url.getProtocol());
    }

    private static void createFileFromZipFile(File file, ZipFile zipFile, ZipEntry zipEntry) throws IOException {
        if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
            throw new IOException("Can not create parent directory for " + file.toString());
        }
        file.createNewFile();
        FileOutputStream fout = null;
        FileChannel out = null;
        InputStream in = null;
        try {
            fout = new FileOutputStream(file);
            out = fout.getChannel();
            in = zipFile.getInputStream(zipEntry);
            out.transferFrom(Channels.newChannel(in), 0, Integer.MAX_VALUE);
        } finally {
            if (out != null)
                out.close();
            if (in != null)
                in.close();
            if (fout != null)
                fout.close();
        }
    }
}

Related

  1. copyTree(File srcFile, File trgFile)
  2. copyTree(final File source, final File dest)
  3. copyURLToFile(URL in, File out)
  4. copyUsingNIO(String src, String dest)
  5. copyWithChannels(File aSourceFile, File aTargetFile, boolean aAppend)
  6. doCopyDirectory(File srcDir, File destDir, boolean preserveFileDate, List exclusionList)
  7. doCopyFile(File srcFile, File destFile, boolean preserveFileDate)
  8. doCopyFile(File srcFile, File destFile, boolean preserveFileDate)
  9. fCopy(FileInputStream src, File dest)