Java FileChannel Copy fileStreamCopy(FileInputStream in, FileOutputStream out, boolean closeOutput)

Here you can find the source of fileStreamCopy(FileInputStream in, FileOutputStream out, boolean closeOutput)

Description

Optimized copy for file streams using java.nio channels.

License

Open Source License

Return

number of bytes transferred.

Declaration

public static long fileStreamCopy(FileInputStream in, FileOutputStream out, boolean closeOutput)
        throws IOException 

Method Source Code

//package com.java2s;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import java.nio.channels.FileChannel;

public class Main {
    public static final int NIO_CHANNEL_CHUNK_SIZE = 4 * 1024 * 1024;

    /**/*from  ww  w.java  2  s . c  o m*/
     * Optimized copy for file streams using java.nio channels. If both
     * input stream and output stream are actually file streams, then this
     * method should be faster than {@link #pipe(java.io.InputStream, java.io.OutputStream, int, boolean) }.
     * 
     * @return number of bytes transferred.
     * 
     * @see #pipe(java.io.InputStream, java.io.OutputStream, int, boolean) 
     */
    public static long fileStreamCopy(FileInputStream in, FileOutputStream out, boolean closeOutput)
            throws IOException {
        FileChannel src = in.getChannel();
        FileChannel dst = out.getChannel();
        long pos = 0;
        long n;
        try {
            while ((n = dst.transferFrom(src, pos, NIO_CHANNEL_CHUNK_SIZE)) > 0) {
                pos += n;
            }
        } finally {
            src.close();
            if (closeOutput) {
                dst.close();
            }
        }
        return pos;
    }
}

Related

  1. doCopyFile(File srcFile, File destFile, boolean preserveFileDate)
  2. doCopyFile(File srcFile, File destFile, boolean preserveFileDate)
  3. fCopy(FileInputStream src, File dest)
  4. fileChannelCopy(File src, File dest)
  5. fileCopy(String sourceFolder, String destinationFolder)
  6. nioCopy(File source, File target, FilenameFilter filter)
  7. nioCopy(FileOutputStream fos, FileInputStream fis)
  8. nioCopyFile(File source, File target, boolean replaceIfExists)
  9. touchcopy(File src, File dest)