Java File Copy nio copyFile(File src, File dest)

Here you can find the source of copyFile(File src, File dest)

Description

copy File

License

Apache License

Declaration

public static void copyFile(File src, File dest) throws IOException 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Main {
    private static final int MAX_BUFFER_SIZE = 4096;

    public static void copyFile(File src, File dest) throws IOException {
        FileInputStream input = null;
        FileChannel inputChannel = null;
        FileOutputStream output = null;
        FileChannel outputChannel = null;
        try {/*w w w  .ja va 2  s  . c om*/
            input = new FileInputStream(src);
            inputChannel = input.getChannel();
            output = new FileOutputStream(dest);
            outputChannel = output.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(MAX_BUFFER_SIZE);
            for (;;) {
                buffer.clear();
                if ((-1) == inputChannel.read(buffer))
                    break;
                buffer.flip();
                outputChannel.write(buffer);
            }
        } finally {
            if (outputChannel != null)
                close(outputChannel);
            if (output != null)
                close(output);
        }
    }

    private static void close(InputStream input) {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
            }
        }
    }

    private static void close(OutputStream output) {
        if (output != null) {
            try {
                output.close();
            } catch (IOException e) {
            }
        }
    }

    private static void close(FileChannel channel) {
        if (channel != null) {
            try {
                channel.close();
            } catch (IOException e) {
            }
        }
    }
}

Related

  1. copy(File srcFile, File dstFile)
  2. copy(File srcFileOrDir, File targetFileOrDir)
  3. copy(File toFile, File fromFile)
  4. copyFile(File f1, File f2)
  5. copyFile(File source, File dest, boolean visibleFilesOnly)
  6. copyFile(FileChannel srcFc, File dstFile)
  7. copyFile(final File source, final File dest)
  8. copyFile(final File source, final File target)
  9. copyFile(final File source, final File target)