write Device Binary To File - Android java.io

Android examples for java.io:BufferedOutputStream

Description

write Device Binary To File

Demo Code

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class Main {

  public static void writeDeviceBinaryToFile(final String folderPath, final String fileName, byte[] bytes,
      String extension) {// w w  w .j a va  2 s .  c  o m
    String filePath = String.format("%1$s/%2$s.%3$s", folderPath, fileName, extension);
    writeDeviceBinaryToFile(filePath, bytes);
  }

  private static void writeDeviceBinaryToFile(String filePath, byte[] bytes) {
    File file;
    OutputStream output = null;

    try {
      file = new File(filePath);

      if (!file.getParentFile().exists()) {
        file.getParentFile().mkdirs();
      }

      if (file.getParentFile().isDirectory() && !file.exists()) {
        file.createNewFile();
      }

      if (!file.canWrite()) {
        file.setWritable(true);
      }

      try {
        output = new BufferedOutputStream(new FileOutputStream(filePath, true));
        output.write(bytes);
      } finally {
        output.close();
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }

  }

Related Tutorials