Java FileChannel Copy nioCopyFile(File source, File target, boolean replaceIfExists)

Here you can find the source of nioCopyFile(File source, File target, boolean replaceIfExists)

Description

nio Copy File

License

Open Source License

Declaration

private static void nioCopyFile(File source, File target, boolean replaceIfExists) throws IOException 

Method Source Code


//package com.java2s;

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

import java.io.IOException;

import java.nio.channels.FileChannel;

public class Main {
    private static void nioCopyFile(File source, File target, boolean replaceIfExists) throws IOException {
        if (!target.createNewFile()) // atomic
        {//ww  w .  ja  va  2s.  com
            if (target.exists() && !replaceIfExists) {
                throw new IOException(String.format("File '%s' already exists. ", target.getAbsolutePath()));
            }
        }
        FileInputStream sourceStream = null;
        FileOutputStream targetStream = null;
        FileChannel sourceChannel = null;
        FileChannel targetChannel = null;
        try {
            sourceStream = new FileInputStream(source);
            targetStream = new FileOutputStream(target);
            sourceChannel = sourceStream.getChannel();
            targetChannel = targetStream.getChannel();
            final long size = sourceChannel.size();
            long transferred = 0L;
            while (transferred < size) {
                transferred += targetChannel.transferFrom(sourceChannel, transferred, (size - transferred));
            }
        } finally {
            if (sourceChannel != null) {
                sourceChannel.close();
            }
            if (targetChannel != null) {
                targetChannel.close();
            }
            if (sourceStream != null) {
                sourceStream.close();
            }
            if (targetStream != null) {
                targetStream.close();
            }
        }
    }
}

Related

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