Android File to Byte Array Read getBytesFromFile(File file, long startPostion, long numberOfBytesToRead)

Here you can find the source of getBytesFromFile(File file, long startPostion, long numberOfBytesToRead)

Description

get Bytes From File

Declaration

public static byte[] getBytesFromFile(File file, long startPostion,
            long numberOfBytesToRead) throws IOException 

Method Source Code

//package com.java2s;
import java.io.ByteArrayOutputStream;

import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;

public class Main {
    /** The BUFFER_SIZE of 128 kb. */
    private final static int BUFFER_SIZE = 1024 * 128;

    public static byte[] getBytesFromFile(File file, long startPostion,
            long numberOfBytesToRead) throws IOException {
        try (FileInputStream fis = new FileInputStream(file);
                ByteArrayOutputStream ous = new ByteArrayOutputStream()) {
            fis.skip(startPostion);/*from w w  w  .ja  v a 2 s .  com*/

            byte[] dataBytes = new byte[BUFFER_SIZE];

            long totalRead = 0;
            int nread = 0;
            while ((nread = fis.read(dataBytes)) != -1
                    && (totalRead <= numberOfBytesToRead || numberOfBytesToRead == -1)) {
                ous.write(dataBytes, 0, nread);
                totalRead += nread;
            }

            return ous.toByteArray();
        }
    }
}

Related

  1. getBytes(File file)
  2. getBytes(File file)
  3. getBytesFromFile(File file)
  4. getFileAsByteArray(File file)
  5. getFileAsByteArrayOutputStream( File file)
  6. readBytes(@NotNull File file)
  7. readBytes(@NotNull String filePath)