Converts the input stream to a byte array. - Android File Input Output

Android examples for File Input Output:Byte Array Convert

Description

Converts the input stream to a byte array.

Demo Code

/*/*from w  ww.j  a  v  a2  s .  c  o  m*/
 * Copyright 2013 Kevin Quan (kevin.quan@gmail.com)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Locale;
import android.util.Log;

public class Main{
    private static final String TAG = ByteUtils.class.getSimpleName();
    /**
     * Converts the input stream to a byte array.  The reading of the input stream is not buffered.  The input stream will not be closed.
     * @param stream The stream to convert
     * @return A byte array with the contents of the stream
     */
    public static byte[] convertStreamToByteArray(InputStream stream) {
        if (stream == null) {
            return new byte[] {};
        }
        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        byte[] data = new byte[Short.MAX_VALUE - 1];
        int read = -1;

        try {
            while ((read = stream.read(data, 0, data.length)) != -1) {
                buf.write(data, 0, read);
            }
            buf.flush();
        } catch (IOException ioe) {
            Log.e(TAG, "Could not read from stream.", ioe);
        }
        try {
            return buf.toByteArray();
        } finally {
            try {
                buf.close();
            } catch (IOException ioe) {
            }
        }
    }
}

Related Tutorials