Now you can Subscribe using RSS

Submit your Email


Convert File to Byte Array in Android

Vishal Shrestha
There can be some scenarios where you will want to convert ByteArray to a File like bytearray to bitmap or audio files or any other type of file in your Android App. Simply speaking a byte array is an array of bytes, a byte consists of 8 bit. Byte array can be use dto store the collection of binary data like the contents of a file.

The following code shows how you can convert byte array to a file and a file to byte array in Android.

Convet File to Byte Array and Vice Versa

Converting File to Byte Array in Android
You can do this using input streams.
public static byte[] getByteArrayFromAudio(String filePath) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(filePath);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            for (int readNum; (readNum = != -1; ) {
                bos.write(b, 0, readNum);
            return bos.toByteArray();
        } catch (Exception e) {
            Log.d("mylog", e.toString());
        return null;

Converting Byte Array to File in Android
You can do this using buffered output streams.
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(yourFile));

For example, the code below shows how you can convert a bitmap to a byte array and vice-versa.

Bitmap to Byte Array:
public static byte[] getByteArray(Bitmap bitmap) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 0, byteArrayOutputStream);
        return byteArrayOutputStream.toByteArray();

Byte Array to Bitmap:
Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);


Vishal Shrestha / Author & Founder

A developer by profession, a born Adventurer. I mainly do Android but like to get my hands dirty with web development and a little bit of Python. I would't rather go on a Trek than a party and you can find me having a few rounds with the heavy bag to let out the steam ;)


Research and Development at : Ekghanti

Mobile Technology Lead at : Vimvox Lab

For Business info : My Portfolio Site


Post a Comment

Coprights @ 2017 | The Code City by Vishal Shrestha Vishal Shrestha