Load stream To Byte Array - Android File Input Output

Android examples for File Input Output:Byte Array Convert

Description

Load stream To Byte Array

Demo Code


//package com.java2s;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Main {
    private static final int DEFAULT_READ_LENGTH = 8192;

    private static byte[] streamToByteArray(final InputStream inputStream)
            throws IOException {
        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(
                DEFAULT_READ_LENGTH); /*  ww  w.jav a 2  s.  c o  m*/
        final byte[] bytes = new byte[DEFAULT_READ_LENGTH];
        final BufferedInputStream bis = new BufferedInputStream(
                inputStream, DEFAULT_READ_LENGTH);

        try {
            int len;
            while ((len = bis.read(bytes, 0, DEFAULT_READ_LENGTH)) > 0) {
                outputStream.write(bytes, 0, len);
            }
            return outputStream.toByteArray();

        } finally {
            closeStream(outputStream);
        }
    }

    private static void closeStream(final OutputStream stream) {
        if (stream == null)
            return;
        try {
            stream.close();
        } catch (final IOException ignored) {
        }
    }
}

Related Tutorials