Java FileChannel Copy copyAll(File source, File targetDir)

Here you can find the source of copyAll(File source, File targetDir)

Description

copy All

License

Open Source License

Declaration

public static void copyAll(File source, File targetDir) throws IOException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

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

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStream;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;

public class Main {
    public static void copyAll(File source, File targetDir) throws IOException {
        if (!targetDir.isDirectory()) {
            throw new RuntimeException("Cannot copy files to a file that is not a directory.");
        }//from  w  ww .  j a  va 2  s.  c  o  m
        File target = new File(targetDir, source.getName());

        if (source.isDirectory()) {
            if (!target.mkdir()) {
                throw new RuntimeException("Cannot create directory " + target.getAbsolutePath());
            }
            for (File f : source.listFiles()) {
                copyAll(f, target);
            }
        } else {
            copyFile(source, target);
        }
    }

    public static void copyFile(File in, File out) throws IOException {
        out.getParentFile().mkdirs();
        FileOutputStream outStream = new FileOutputStream(out);
        try {
            copyFileToStream(in, outStream);
        } finally {
            outStream.close();
        }
    }

    public static void copyFileToStream(File in, OutputStream out) throws IOException {
        FileInputStream is = new FileInputStream(in);
        FileChannel inChannel = is.getChannel();
        WritableByteChannel outChannel = Channels.newChannel(out);
        try {
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } finally {
            if (is != null)
                is.close();
            if (inChannel != null)
                inChannel.close();
            if (outChannel != null)
                outChannel.close();
        }
    }
}

Related

  1. copy(String sourceFile, String targetFile)
  2. copy0(File src, File dest)
  3. copy12(File file1, File file2)
  4. copy2(String sourceFileName, String destFileName)
  5. copyAFile(File source, File target)
  6. copyAndReplace(File from, File to)
  7. copyChannel(ReadableByteChannel in, long length, FileChannel out)
  8. copyFile(File aFromFile, String aToFilename)
  9. copyFile(File copyFrom, File copyTo)