Java FileChannel Copy copy(FileInputStream iStream, FileOutputStream oStream)

Here you can find the source of copy(FileInputStream iStream, FileOutputStream oStream)

Description

Special optimized version of copying a FileInputStream to a FileOutputStream .

License

Open Source License

Parameter

Parameter Description
iStream a parameter
oStream a parameter

Exception

Parameter Description
IOException an exception

Declaration

private static void copy(FileInputStream iStream, FileOutputStream oStream) throws IOException 

Method Source Code

//package com.java2s;
/**//from w  w  w  . j a  v  a 2s.  c  o  m
 * Aptana Studio
 * Copyright (c) 2005-2012 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the GNU Public License (GPL) v3 (with exceptions).
 * Please see the license.html included with this distribution for details.
 * Any modifications to this file must keep this entire header intact.
 */

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

import java.nio.channels.FileChannel;

public class Main {
    /**
     * Special optimized version of copying a {@link FileInputStream} to a {@link FileOutputStream}. Uses
     * {@link FileChannel#transferTo(long, long, java.nio.channels.WritableByteChannel)}. Closes the streams after
     * copying.
     * 
     * @param iStream
     * @param oStream
     * @throws IOException
     */
    private static void copy(FileInputStream iStream, FileOutputStream oStream) throws IOException {
        try {
            FileChannel inChannel = iStream.getChannel();
            FileChannel outChannel = oStream.getChannel();
            long fileSize = inChannel.size();
            long offs = 0, doneCnt = 0, copyCnt = Math.min(65536, fileSize);
            do {
                doneCnt = inChannel.transferTo(offs, copyCnt, outChannel);
                offs += doneCnt;
                fileSize -= doneCnt;
            } while (fileSize > 0);
        } finally {
            try {
                if (iStream != null) {
                    iStream.close();
                }
            } catch (Exception e) {
                // ignore
            }

            try {
                if (oStream != null) {
                    oStream.close();
                }
            } catch (Exception e) {
                // ignore
            }
        }
    }
}

Related

  1. copy(FileInputStream in, FileOutputStream out)
  2. copy(FileInputStream inputStream, FileOutputStream outputStream)
  3. copy(final File aCopyFrom, final File aCopyTo)
  4. copy(final File fromFile, final File toFile)
  5. copy(final File source, final File dest)
  6. copy(final File src, File dst, final boolean overwrite)