Java File Copy copyFiles(File src, File dest)

Here you can find the source of copyFiles(File src, File dest)

Description

Copy files.

License

Open Source License

Parameter

Parameter Description
src the src
dest the dest

Exception

Parameter Description
IOException Signals that an I/O exception has occurred.

Declaration

public static void copyFiles(File src, File dest) throws IOException 

Method Source Code


//package com.java2s;
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 {
    /**/*from w  w w.j ava  2s .  c o  m*/
     * Copy files.
     *
     * @param src
     *            the src
     * @param dest
     *            the dest
     * @throws IOException
     *             Signals that an I/O exception has occurred.
     */
    public static void copyFiles(File src, File dest) throws IOException {
        if (!src.exists()) {
            throw new IOException("Resource does not exist: " + src.getAbsolutePath());
        } else if (!src.canRead()) {
            throw new IOException("Insufficient privileges to open: " + src.getAbsolutePath());
        }
        if (src.isDirectory()) {
            if (!dest.exists() || !dest.mkdirs()) {
                throw new IOException("Cannot create: " + dest.getAbsolutePath());
            }
            String list[] = src.list();
            for (int i = 0; i < list.length; i++) {
                File to = new File(dest, list[i]);
                File from = new File(src, list[i]);
                copyFiles(from, to);
            }
        } else {
            streamCopy(new FileInputStream(src), new FileOutputStream(dest));
        }
    }

    /**
     * Stream copy.
     *
     * @param is
     *            the is
     * @param os
     *            the os
     * @throws IOException
     *             Signals that an I/O exception has occurred.
     */
    public static void streamCopy(InputStream is, OutputStream os) throws IOException {
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = is.read(buffer)) >= 0) {
            os.write(buffer, 0, bytesRead);
        }
        is.close();
        os.close();
    }
}

Related

  1. copyFiles(File file, File destPath)
  2. copyFiles(File fromDir, File toDir)
  3. copyFiles(File source, File destination)
  4. copyFiles(File sourceFile, File targetDir)
  5. copyFiles(File src, File dest)
  6. copyFiles(File src, File dest, boolean override)
  7. copyFiles(File src, File dest, FilenameFilter filter)
  8. copyFiles(File src, File dest, String... filenameExtension)
  9. copyFiles(File srcDir, File destDir, String... regexps)