Java FileChannel Copy copy(FileInputStream inputStream, FileOutputStream outputStream)

Here you can find the source of copy(FileInputStream inputStream, FileOutputStream outputStream)

Description

copy

License

Open Source License

Declaration

public static void copy(FileInputStream inputStream, FileOutputStream outputStream) throws Exception 

Method Source Code


//package com.java2s;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;

public class Main {
    public static void copy(File from, File to) throws Exception {
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
        try {/*w w  w. j  av a2 s  .c  om*/
            outputStream = new FileOutputStream(to);
            inputStream = new FileInputStream(from);

            copy(inputStream, outputStream);

            outputStream.close();
            inputStream.close();
        } finally {
            try {
                if (outputStream != null)
                    outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                if (inputStream != null)
                    inputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void copy(FileInputStream inputStream, FileOutputStream outputStream) throws Exception {
        FileChannel srcChannel = null;
        FileChannel desChannel = null;

        try {
            srcChannel = inputStream.getChannel();
            desChannel = outputStream.getChannel();

            srcChannel.transferTo(0, srcChannel.size(), desChannel);

            srcChannel.close();
            desChannel.close();
        } finally {
            try {
                if (srcChannel != null)
                    srcChannel.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                if (desChannel != null)
                    desChannel.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Related

  1. copy(FileInputStream in, FileOutputStream out)
  2. copy(FileInputStream iStream, FileOutputStream oStream)
  3. copy(final File aCopyFrom, final File aCopyTo)
  4. copy(final File fromFile, final File toFile)
  5. copy(final File source, final File dest)