Android : How to read file in bytes? Android : How to read file in bytes? android android

Android : How to read file in bytes?


here it's a simple:

File file = new File(path);int size = (int) file.length();byte[] bytes = new byte[size];try {    BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));    buf.read(bytes, 0, bytes.length);    buf.close();} catch (FileNotFoundException e) {    // TODO Auto-generated catch block    e.printStackTrace();} catch (IOException e) {    // TODO Auto-generated catch block    e.printStackTrace();}

Add permission in manifest.xml:

 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


The easiest solution today is to used Apache common io :

http://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/FileUtils.html#readFileToByteArray(java.io.File)

byte bytes[] = FileUtils.readFileToByteArray(photoFile)

The only drawback is to add this dependency in your build.gradle app :

implementation 'commons-io:commons-io:2.5'

+ 1562 Methods count


Here is a solution that guarantees entire file will be read, that requires no libraries and is efficient:

byte[] fullyReadFileToBytes(File f) throws IOException {    int size = (int) f.length();    byte bytes[] = new byte[size];    byte tmpBuff[] = new byte[size];    FileInputStream fis= new FileInputStream(f);;    try {        int read = fis.read(bytes, 0, size);        if (read < size) {            int remain = size - read;            while (remain > 0) {                read = fis.read(tmpBuff, 0, remain);                System.arraycopy(tmpBuff, 0, bytes, size - remain, read);                remain -= read;            }        }    }  catch (IOException e){        throw e;    } finally {        fis.close();    }    return bytes;}

NOTE: it assumes file size is less than MAX_INT bytes, you can add handling for that if you want.