Copy in File to out File using FileChannels. - Java java.nio.channels

Java examples for java.nio.channels:FileChannel

Description

Copy in File to out File using FileChannels.

Demo Code


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Main{
    /**/* ww  w .j  a  va2  s. co m*/
     * my logger for debug and error-output.
     */
    static final Logger LOG = Logger.getLogger(SystemUtils.class.getName());
    /**
     * Copy inFile to outFile using FileChannels.
     * @param inFile input file
     * @param outFile output file
     * @return tue if the copy-operation was a success
     */
    public static boolean copyFile(final File inFile, final File outFile) {
        try {
            FileChannel ic = new FileInputStream(inFile).getChannel();
            FileChannel oc = new FileOutputStream(outFile).getChannel();
            ic.transferTo(0, ic.size(), oc);
            ic.close();
            oc.close();
            return true;
        } catch (IOException e) {
            SystemUtils.LOG.log(
                    Level.INFO,
                    "SystemUtils.copyFile() Exception while copy file "
                            + inFile.getAbsolutePath() + " to "
                            + outFile.getAbsolutePath(), e);
            return false;
        }
    }
}

Related Tutorials