Android File to Byte Array Read getFileAsByteArray(File file)

Here you can find the source of getFileAsByteArray(File file)

Description

get File As Byte Array

Parameter

Parameter Description
filename a parameter

Declaration

public static byte[] getFileAsByteArray(File file) throws IOException 

Method Source Code

//package com.java2s;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Main {
    /**//from   w  w  w  . j ava2s.  c om
     *
     * @param filename
     * @return
     * @deprecated Used IOUtil.getFileAsByteArrayOutputStream
     */
    public static byte[] getFileAsByteArray(File file) throws IOException {

        return getFileAsByteArrayOutputStream(file).toByteArray();

    }

    /**
     *
     * @return
     * @param filename
     * @throws java.io.IOException
     * @deprecated Used IOUtil.getFileAsByteArrayOutputStream
     */
    public static ByteArrayOutputStream getFileAsByteArrayOutputStream(
            File file) throws IOException {

        InputStream in = null;
        String tmpFilename = null;
        OutputStream out = null;
        byte[] buf = new byte[1024 * 8];
        int len = 0;

        try {

            // Open the file
            in = new FileInputStream(file);

            // Open the output byte array
            out = new ByteArrayOutputStream();

            // Transfer bytes from the ZIP file to the output file
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }

            // Close the streams
            out.close();
            in.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

        return (ByteArrayOutputStream) out;

    }
}

Related

  1. getBytes(File file)
  2. getBytes(File file)
  3. getBytesFromFile(File file)
  4. getBytesFromFile(File file, long startPostion, long numberOfBytesToRead)
  5. getFileAsByteArrayOutputStream( File file)
  6. readBytes(@NotNull File file)
  7. readBytes(@NotNull String filePath)
  8. readFileBytes(File fx)