Java FileChannel Copy copyFile(File src, File dst)

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

Description

copies the contents of a file

License

Open Source License

Declaration

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

Method Source Code


//package com.java2s;
/*// w  w  w  .  j a v  a 2  s.  c  o  m
 * This file is part of the Jose Project
 * see http://jose-chess.sourceforge.net/
 * (c) 2002-2006 Peter Sch?fer
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 */

import java.io.*;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;

public class Main {
    /**
    * copies the contents of a file
    */
    public static void copyFile(File src, File dst) throws IOException {
        FileInputStream in = new FileInputStream(src);
        FileOutputStream out = new FileOutputStream(dst);

        copyChannel(in.getChannel(), src.length(), (WritableByteChannel) out.getChannel());

        in.close();
        out.close();
    }

    /**
     * copies the contents of a file
     */
    public static long copyFile(File src, OutputStream out) throws IOException {
        FileInputStream in = new FileInputStream(src);

        WritableByteChannel cout = Channels.newChannel(out);
        long result = copyChannel(in.getChannel(), src.length(), cout);

        in.close();
        return result;
    }

    public static long copyChannel(FileChannel in, long length, WritableByteChannel out) throws IOException {
        if (length < 0L || length >= Integer.MAX_VALUE)
            return in.transferTo(0L, length, out);

        long result = 0L;
        while (result < length)
            result += in.transferTo(result, length - result, out);
        return result;
    }

    public static long copyChannel(ReadableByteChannel in, long length, FileChannel out) throws IOException {
        if (length < 0L || length >= Integer.MAX_VALUE)
            return out.transferFrom(in, 0L, length);

        long result = 0L;
        while (result < length)
            result += out.transferFrom(in, result, length - result);
        return result;
    }
}

Related

  1. copyFile(File src, File dest)
  2. copyFile(File src, File destination)
  3. copyFile(File src, File destination)
  4. copyFile(File src, File dst)
  5. copyFile(File src, File dst)
  6. copyFile(File src, File dst)
  7. copyFile(File src, File dst)
  8. copyFile(File src, File target)
  9. copyFile(File src, File target)