Java FileChannel Copy copyFile(String fromFileName, String toFileName)

Here you can find the source of copyFile(String fromFileName, String toFileName)

Description

copy File

License

Open Source License

Declaration

public static boolean copyFile(String fromFileName, String toFileName) throws IOException 

Method Source Code

//package com.java2s;
/*// w w  w  .  j  a  v  a 2s.  c o  m
 * (C) Copyright IBM Corp. 2008
 *
 * LICENSE: Eclipse Public License v1.0
 * http://www.eclipse.org/legal/epl-v10.html
 */

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

import java.io.IOException;

import java.nio.channels.FileChannel;

public class Main {
    public static boolean copyFile(String fromFileName, String toFileName) throws IOException {
        return copyFile(new File(fromFileName), new File(toFileName));
    }

    public static boolean copyFile(File fromFile, File toFile) throws IOException {

        //      System.out.println("Testing if files exist. "
        //            + "fromFile: " + fromFile.getCanonicalPath() + ": " + fromFile.exists()
        //            + "; toFile: " + toFile.getCanonicalPath() + ": " + toFile.exists()
        //      );

        if (!fromFile.exists())
            return false;
        if (!toFile.exists())
            toFile.createNewFile();
        FileChannel fromChannel = null, toChannel = null;

        try {
            fromChannel = new FileInputStream(fromFile).getChannel();
            toChannel = new FileOutputStream(toFile).getChannel();
            toChannel.transferFrom(fromChannel, 0, fromChannel.size());
            return true;
        } finally {
            if (null != fromChannel)
                fromChannel.close();
            if (null != toChannel)
                toChannel.close();
        }
    }
}

Related

  1. copyFile(final String src, final String dst)
  2. copyFile(InputStream is, OutputStream os)
  3. copyFile(java.io.File fromFile, java.io.File toFile)
  4. copyFile(java.io.File in, java.io.File out)
  5. copyFile(Path source, Path target)
  6. copyFile(String fromPath, String toPath)
  7. copyFile(String in, String out)
  8. copyFile(String infile, String outfile)
  9. copyFile(String inFile, String outFile)