copy File using FileChannel - Android java.nio.channels

Android examples for java.nio.channels:FileChannel

Description

copy File using FileChannel

Demo Code

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;

import android.os.Environment;

public class Main {

  public static boolean copyFileTo(FileInputStream originFile, File destinationFile) {

    boolean exportDone = true;

    try {/*from ww  w .  ja v a 2  s .  c  o  m*/
      File sd = Environment.getExternalStorageDirectory();

      if (sd.canWrite()) {

        // Create parent directories
        destinationFile.getParentFile().mkdirs();

        FileChannel src = originFile.getChannel();
        FileChannel dst = new FileOutputStream(destinationFile).getChannel();
        dst.transferFrom(src, 0, src.size());
        src.close();
        dst.close();
      }
    } catch (Exception e) {
      exportDone = false;
    }
    return exportDone;
  }

  public static boolean copyFileTo(File originFile, File destinationFile) {
    try {
      return copyFileTo(new FileInputStream(originFile), destinationFile);
    } catch (FileNotFoundException e) {
      return false;
    }
  }

}

Related Tutorials