Android File to Byte Array Read buildDataFromFile(String path)

Here you can find the source of buildDataFromFile(String path)

Description

build Data From File

Declaration

public static byte[] buildDataFromFile(String path) 

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  v a 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. readBytes(File file)
  2. readBytes(String path)
  3. readFromFile(String fileName, int offset, int len)
  4. read(File file)
  5. buildDataFromFile(File file)
  6. buildDataFromFile(String path, int bufferSize)
  7. file2byte(File file)
  8. file2byte(String path)
  9. getByteFromFile(String fileName)