Java FileChannel Copy copyFileByChannel(String srcFileName, String dstFileName)

Here you can find the source of copyFileByChannel(String srcFileName, String dstFileName)

Description

copy File By Channel

License

Apache License

Declaration

public static void copyFileByChannel(String srcFileName, String dstFileName) throws IOException 

Method Source Code


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

import java.io.Closeable;

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 final static int COPY_FILE_SIZE = 1024 * 1024;

    public static void copyFileByChannel(String srcFileName, String dstFileName) throws IOException {
        File srcFile = new File(srcFileName);
        File dstFile = new File(dstFileName);
        if (!srcFile.exists())
            throw new RuntimeException("src file not exists!");
        if (dstFile.exists())
            throw new RuntimeException("dst file exists!");
        FileChannel inFileChannel = null;
        FileChannel outFileChannel = null;
        FileInputStream in = new FileInputStream(srcFile);
        FileOutputStream out = new FileOutputStream(dstFile);
        try {/*from  www .  ja v a2s . c  o m*/
            long position = 0;
            inFileChannel = in.getChannel();
            outFileChannel = out.getChannel();
            while (position < inFileChannel.size()) {
                long realCopy = outFileChannel.transferFrom(inFileChannel, position, COPY_FILE_SIZE);
                position += realCopy;
            }
            inFileChannel.transferTo(0, srcFile.length(), outFileChannel);
        } finally {
            closeStream(in, out);
        }
    }

    public static void closeStream(Closeable... streams) {
        if (streams == null)
            return;
        for (Closeable stream : streams) {
            CloseOneStream(stream);
        }
    }

    private static void CloseOneStream(Closeable stream) {
        if (stream != null) {
            try {
                stream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Related

  1. copyFile(String sourceFilename, String destFilename)
  2. copyFile(String sourceFileName, String destinationFileName)
  3. copyFile(String src, String dest)
  4. copyFile(String srcFileName, String desFileName)
  5. copyFile(String srcPath, String destPath)
  6. copyFileContent(final String sourcePath, final String targetPath)
  7. copyFileIntoProjectFolder(String projectName, File file)
  8. copyFileLocking(File copyFrom, File copyTo)
  9. copyFileNIO(File src, File dest)