Java FileChannel Copy nioCopy(FileOutputStream fos, FileInputStream fis)

Here you can find the source of nioCopy(FileOutputStream fos, FileInputStream fis)

Description

Copy a single file using NIO.

License

Open Source License

Exception

Parameter Description
IOException an exception

Declaration

private static void nioCopy(FileOutputStream fos, FileInputStream fis) 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 long MAX_TRANSFER_SIZE = Long.getLong("gemfire.FileUtil.MAX_TRANSFER_SIZE", 1024 * 1024)
            .longValue();/*  w ww . ja v a 2 s.co m*/

    /**
     * Copy a single file using NIO.
     * @throws IOException
     */
    private static void nioCopy(FileOutputStream fos, FileInputStream fis) throws IOException {
        FileChannel outChannel = fos.getChannel();
        FileChannel inChannel = fis.getChannel();
        long length = inChannel.size();
        long offset = 0;
        while (true) {
            long remaining = length - offset;

            long toTransfer = remaining < MAX_TRANSFER_SIZE ? remaining : MAX_TRANSFER_SIZE;
            long transferredBytes = inChannel.transferTo(offset, toTransfer, outChannel);
            offset += transferredBytes;
            length = inChannel.size();
            if (offset >= length) {
                break;
            }
        }
    }
}

Related

  1. fCopy(FileInputStream src, File dest)
  2. fileChannelCopy(File src, File dest)
  3. fileCopy(String sourceFolder, String destinationFolder)
  4. fileStreamCopy(FileInputStream in, FileOutputStream out, boolean closeOutput)
  5. nioCopy(File source, File target, FilenameFilter filter)
  6. nioCopyFile(File source, File target, boolean replaceIfExists)
  7. touchcopy(File src, File dest)
  8. tryCopyFile(File sourceLocation, File targetLocation)