copy File, Write the specified data to an specified file - Android java.io

Android examples for java.io:File Copy

Description

copy File, Write the specified data to an specified file

Demo Code

import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main {

  private static final int DEFAULT_BUFFER_SIZE = 8192;

  /**/*  ww  w.  j a v a  2s  . c  om*/
   * Write the specified data to an specified file.
   * 
   * @param file
   *          The file to write into.
   * @param data
   *          The data to write. May be null.
   */
  public static final void copyFile(final File srcFile, final File destFile) {
    if (null == srcFile) {
      throw new IllegalArgumentException("srcFile may not be null.");
    }
    if (null == destFile) {
      throw new IllegalArgumentException("destFile may not be null.");
    }
    FileInputStream fis = null;
    FileOutputStream fos = null;
    try {
      fis = new FileInputStream(srcFile);
      fos = new FileOutputStream(destFile);
      final byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
      int bytesRead = fis.read(buffer);
      while (bytesRead > 0) {
        fos.write(buffer);
        bytesRead = fis.read(buffer);
      }
    } catch (final FileNotFoundException e) {
      e.printStackTrace();
    } catch (final IOException e) {
      e.printStackTrace();
    } finally {
      quietClose(fis);
      quietClose(fos);
    }
  }

  /**
   * Close an {@linkplain Closeable} quietly.
   * 
   * @param closeable
   *          the {@linkplain Closeable} to close.
   */
  public static final void quietClose(final Closeable closeable) {
    if (closeable != null) {
      try {
        closeable.close();
      } catch (final IOException e) {
        // Ignore errors.
      }
    }
  }

}

Related Tutorials