Android File to Byte Array Read buildDataFromFile(String path, int bufferSize)

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

Description

build Data From File

Declaration

public static byte[] buildDataFromFile(String path, int bufferSize) 

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());
    }/*  ww  w. j  ava2 s .c o  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(String path)
  2. readFromFile(String fileName, int offset, int len)
  3. read(File file)
  4. buildDataFromFile(File file)
  5. buildDataFromFile(String path)
  6. file2byte(File file)
  7. file2byte(String path)
  8. getByteFromFile(String fileName)
  9. getAvailableBytes(File root)