Android File to Byte Array Read buildDataFromFile(File file)

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

Description

build Data From File

Declaration

public static byte[] buildDataFromFile(File file) 

Method Source Code

//package com.java2s;

import java.io.ByteArrayOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.InputStream;

public class Main {
    public static byte[] buildDataFromFile(File file) {
        return buildDataFromFile(file.getAbsolutePath());
    }//  w w w .j  a va  2  s  .  co  m

    public static byte[] buildDataFromFile(String path) {
        return buildDataFromFile(path, 1024);
    }

    public static byte[] buildDataFromFile(String path, int bufferSize) {
        InputStream is = null;
        File file = new File(path);
        if (!file.exists()) {
            return null;
        }
        try {
            is = new FileInputStream(file);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        ByteArrayOutputStream baos = null;
        if (is != null) {
            try {
                baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[bufferSize];
                int i = 0;
                while ((i = is.read(buffer)) != -1) {
                    baos.write(buffer, 0, i);
                }
                baos.flush();
                return baos.toByteArray();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if (baos != null) {
                    try {
                        baos.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }
}

Related

  1. getBytesFromFile(File file)
  2. readBytes(File file)
  3. readBytes(String path)
  4. readFromFile(String fileName, int offset, int len)
  5. read(File file)
  6. buildDataFromFile(String path)
  7. buildDataFromFile(String path, int bufferSize)
  8. file2byte(File file)
  9. file2byte(String path)