Java File Copy nio copy(File from, File to)

Here you can find the source of copy(File from, File to)

Description

copy

License

Open Source License

Declaration

public static void copy(File from, File to) throws IOException 

Method Source Code

//package com.java2s;
/**/*  ww w. j  av a2  s . com*/
 * Copyright (C) 2009  HungryHobo@mail.i2p
 * 
 * The GPG fingerprint for HungryHobo@mail.i2p is:
 * 6DD3 EAA2 9990 29BC 4AD2 7486 1E2C 7B61 76DC DC12
 * 
 * This file is part of I2P-Bote.
 * I2P-Bote 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 3 of the License, or
 * (at your option) any later version.
 * 
 * I2P-Bote is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with I2P-Bote.  If not, see <http://www.gnu.org/licenses/>.
 */

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.channels.FileChannel;

public class Main {
    /**
     * Reads all data from an input stream and writes it to an output stream.
     * @param input
     * @param output
     * @throws IOException
     */
    public static void copy(InputStream input, OutputStream output) throws IOException {
        byte[] buffer = new byte[1024 * 1024];
        int bytesRead;
        while ((bytesRead = input.read(buffer)) >= 0)
            output.write(buffer, 0, bytesRead);
    }

    public static void copy(File from, File to) throws IOException {
        if (!to.exists())
            to.createNewFile();

        FileChannel fromChan = null;
        FileChannel toChan = null;
        try {
            fromChan = new FileInputStream(from).getChannel();
            toChan = new FileOutputStream(to).getChannel();
            toChan.transferFrom(fromChan, 0, fromChan.size());
        } finally {
            if (fromChan != null)
                fromChan.close();
            if (toChan != null)
                toChan.close();

            // This is needed on Windows so a file can be deleted after copying it.
            System.gc();
        }
    }
}

Related

  1. copy(File a, File b)
  2. copy(File base_path, File in, File out)
  3. copy(File copied, File destination)
  4. copy(File file, File toDirectory)
  5. copy(File from, File to)
  6. copy(File from, File to)
  7. copy(File from, File to, final boolean recursive, Function excluded)
  8. copy(File in, File out)
  9. copy(File in, File out, boolean overwrite)