convert File To Byte Array - Android java.io

Android examples for java.io:File

Description

convert File To Byte Array

Demo Code

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class Main {

  public static byte[] convertFileToByteArray(File f) {
    byte[] byteArray = null;
    try {/*from w  ww.  j  a  v a 2  s .c  om*/
      InputStream inputStream = new FileInputStream(f);
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      byte[] b = new byte[1024 * 8];
      int bytesRead = 0;

      while ((bytesRead = inputStream.read(b)) != -1) {
        bos.write(b, 0, bytesRead);
      }

      byteArray = bos.toByteArray();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return byteArray;
  }

}

Related Tutorials