Java FileChannel Copy copyWithChannels(File aSourceFile, File aTargetFile, boolean aAppend)

Here you can find the source of copyWithChannels(File aSourceFile, File aTargetFile, boolean aAppend)

Description

copy With Channels

License

Open Source License

Declaration

public static void copyWithChannels(File aSourceFile, File aTargetFile, boolean aAppend) 

Method Source Code

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

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import java.io.IOException;

import java.nio.channels.FileChannel;

public class Main {
    public static void copyWithChannels(File aSourceFile, File aTargetFile, boolean aAppend) {
        ensureTargetDirectoryExists(aTargetFile.getParentFile());
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        FileInputStream inStream = null;
        FileOutputStream outStream = null;
        try {/* w ww  .j  ava  2  s.co  m*/
            try {
                inStream = new FileInputStream(aSourceFile);
                inChannel = inStream.getChannel();
                outStream = new FileOutputStream(aTargetFile, aAppend);
                outChannel = outStream.getChannel();
                long bytesTransferred = 0;
                //defensive loop - there's usually only a single iteration :
                while (bytesTransferred < inChannel.size()) {
                    bytesTransferred += inChannel.transferTo(0, inChannel.size(), outChannel);
                }
            } finally {
                //being defensive about closing all channels and streams 
                if (inChannel != null)
                    inChannel.close();
                if (outChannel != null)
                    outChannel.close();
                if (inStream != null)
                    inStream.close();
                if (outStream != null)
                    outStream.close();
            }
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static void ensureTargetDirectoryExists(File aTargetDir) {
        if (!aTargetDir.exists()) {
            aTargetDir.mkdirs();
        }
    }
}

Related

  1. copyTree(File sourceLocation, File targetLocation)
  2. copyTree(File srcFile, File trgFile)
  3. copyTree(final File source, final File dest)
  4. copyURLToFile(URL in, File out)
  5. copyUsingNIO(String src, String dest)
  6. directoryCopy(URL source, URL destination)
  7. doCopyDirectory(File srcDir, File destDir, boolean preserveFileDate, List exclusionList)
  8. doCopyFile(File srcFile, File destFile, boolean preserveFileDate)
  9. doCopyFile(File srcFile, File destFile, boolean preserveFileDate)