Android File to Byte Array Read readFromFile(String fileName, int offset, int len)

Here you can find the source of readFromFile(String fileName, int offset, int len)

Description

read From File

Declaration

public static byte[] readFromFile(String fileName, int offset, int len) 

Method Source Code

//package com.java2s;

import java.io.File;

import java.io.RandomAccessFile;

import android.util.Log;

public class Main {
    private static final String TAG = "SDK_Sample.Util";

    public static byte[] readFromFile(String fileName, int offset, int len) {
        if (fileName == null) {
            return null;
        }// w  w  w.  j a  v  a  2s . c  o m

        File file = new File(fileName);
        if (!file.exists()) {
            Log.i(TAG, "readFromFile: file not found");
            return null;
        }

        if (len == -1) {
            len = (int) file.length();
        }

        Log.d(TAG, "readFromFile : offset = " + offset + " len = " + len
                + " offset + len = " + (offset + len));

        if (offset < 0) {
            Log.e(TAG, "readFromFile invalid offset:" + offset);
            return null;
        }
        if (len <= 0) {
            Log.e(TAG, "readFromFile invalid len:" + len);
            return null;
        }
        if (offset + len > (int) file.length()) {
            Log.e(TAG, "readFromFile invalid file len:" + file.length());
            return null;
        }

        byte[] b = null;
        try {
            RandomAccessFile in = new RandomAccessFile(fileName, "r");
            b = new byte[len]; // ????????????????????
            in.seek(offset);
            in.readFully(b);
            in.close();

        } catch (Exception e) {
            Log.e(TAG, "readFromFile : errMsg = " + e.getMessage());
            e.printStackTrace();
        }
        return b;
    }
}

Related

  1. fileToBytes(String filePath)
  2. fileToByte(String filePath)
  3. getBytesFromFile(File file)
  4. readBytes(File file)
  5. readBytes(String path)
  6. read(File file)
  7. buildDataFromFile(File file)
  8. buildDataFromFile(String path)
  9. buildDataFromFile(String path, int bufferSize)