Read a byte array value from the specified input stream - Android File Input Output

Android examples for File Input Output:InputStream

Description

Read a byte array value from the specified input stream

Demo Code


//package com.java2s;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

import java.io.IOException;
import java.io.InputStream;

public class Main {
    private static final int BUFSIZ = 4096;

    /**/*from   ww  w . j a  v a  2s.  co m*/
     * Read a byte array value from the specified input stream
     * 
     * @param path
     *            The target file path
     * @return An array value
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static byte[] readAsBytes(final String path)
            throws FileNotFoundException, IOException {
        FileInputStream fis = null;

        try {
            fis = new FileInputStream(path);
            return readAsBytes(fis);
        } finally {
            closeQuietly(fis);
        }
    }

    /**
     * Read a byte array value from the specified input stream
     * 
     * @param is
     *            The target input stream
     * @return An array value
     * @throws IOException
     */
    public static byte[] readAsBytes(final InputStream is)
            throws IOException {
        final byte[] buf = new byte[BUFSIZ];
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();

        for (int n = 0; 0 != (n = is.read(buf));) {
            baos.write(buf, 0, n);
        }

        return baos.toByteArray();
    }

    /**
     * Close the closeables quietly
     * 
     * @param closeables
     *            Instances of {@link Closeable}
     */
    public static void closeQuietly(final Closeable... closeables) {
        if (null == closeables || closeables.length <= 0)
            return;

        for (int i = 0; i < closeables.length; i++) {
            final Closeable closeable = closeables[i];
            if (null == closeable)
                continue;

            try {
                closeables[i].close();
            } catch (IOException e) {
            }
        }
    }
}

Related Tutorials