Copy data from a source stream to destFile. Return true if succeed, return false if failed. - Android java.io

Android examples for java.io:InputStream

Description

Copy data from a source stream to destFile. Return true if succeed, return false if failed.

Demo Code

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class Main {

  /**//from w  ww .  jav a  2  s . c o m
   * Copy data from a source stream to destFile. Return true if succeed, return
   * false if failed.
   */
  public static boolean copyToFile(InputStream inputStream, File destFile) {
    try {
      if (destFile.exists()) {
        destFile.delete();
      }
      FileOutputStream out = new FileOutputStream(destFile);
      try {
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) >= 0) {
          out.write(buffer, 0, bytesRead);
        }
      } finally {
        out.flush();
        try {
          out.getFD().sync();
        } catch (IOException e) {
        }
        out.close();
      }
      return true;
    } catch (IOException e) {
      return false;
    }
  }

}

Related Tutorials