Android File to Byte Array Read readFileBytes(File fx)

Here you can find the source of readFileBytes(File fx)

Description

reads the content of a File and returns a byte array representing the content.

License

Open Source License

Parameter

Parameter Description
fx a parameter

Exception

Parameter Description
IOException an exception

Return

the content of the file in a byte array

Declaration

public static byte[] readFileBytes(File fx) throws IOException 

Method Source Code

//package com.java2s;
/*//from   w w  w  .j  a  v  a2s . c  o m
 *  Copyright (C) 2010-2012 Stichting Akvo (Akvo Foundation)
 *
 *  This file is part of Akvo FLOW.
 *
 *  Akvo FLOW is free software: you can redistribute it and modify it under the terms of
 *  the GNU Affero General Public License (AGPL) as published by the Free Software Foundation,
 *  either version 3 of the License or any later version.
 *
 *  Akvo FLOW is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 *  without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *  See the GNU Affero General Public License included below for more details.
 *
 *  The full license text can also be seen at <http://www.gnu.org/licenses/agpl.html>.
 */

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

import java.io.IOException;

public class Main {
    /**
     * reads the content of a File and returns a byte array representing the content.
     * 
     * @param fx
     * @return the content of the file in a byte array
     * @throws IOException
     */
    public static byte[] readFileBytes(File fx) throws IOException {
        FileInputStream fis;
        fis = new FileInputStream(fx);
        long length = fx.length();
        byte[] bytes = new byte[(int) length];
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length
                && (numRead = fis
                        .read(bytes, offset, bytes.length - offset)) >= 0) {
            offset += numRead;
        }
        fis.close();
        return bytes;
    }
}

Related

  1. getBytesFromFile(File file, long startPostion, long numberOfBytesToRead)
  2. getFileAsByteArray(File file)
  3. getFileAsByteArrayOutputStream( File file)
  4. readBytes(@NotNull File file)
  5. readBytes(@NotNull String filePath)
  6. readFileToByteArray(File file)
  7. readFileToByteArray(String filePath)
  8. fileToBytes(String filePath)
  9. fileToByte(String filePath)