Java InputStream Read Bytes readBytes(InputStream in)

Here you can find the source of readBytes(InputStream in)

Description

Reads all bytes from the supplied input stream and returns them as a byte array.

License

Apache License

Parameter

Parameter Description
in The InputStream supplying the bytes.

Return

A byte array containing all bytes from the supplied input stream.

Declaration

public static byte[] readBytes(InputStream in) throws IOException 

Method Source Code


//package com.java2s;
/*/*from  w  ww  . j a v  a2 s.  c o m*/
 * Copyright (c) 2013. Knowledge Media Institute - The Open University
 *
 * 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.*;

public class Main {
    /**
     * Reads all bytes from the specified file and returns them as a byte array.
     *
     * @param file The file to read.
     * @return A byte array containing all bytes from the specified file.
     * @throws IOException              If an I/O error occurred while reading from the file.
     * @throws IllegalArgumentException If the file size exceeds the maximum array length (larger than
     *                                  {@link Integer#MAX_VALUE}.
     */
    public static byte[] readBytes(File file) throws IOException {
        long fileSize = file.length();
        if (fileSize > Integer.MAX_VALUE) {
            throw new IllegalArgumentException(
                    "File size exceeds maximum array length (" + fileSize + " > " + Integer.MAX_VALUE + ")");
        }

        FileInputStream in = new FileInputStream(file);
        try {
            return readBytes(in, (int) fileSize);
        } finally {
            in.close();
        }
    }

    /**
     * Reads all bytes from the supplied input stream and returns them as a byte
     * array.
     *
     * @param in The InputStream supplying the bytes.
     * @return A byte array containing all bytes from the supplied input stream.
     */
    public static byte[] readBytes(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
        transfer(in, out);
        return out.toByteArray();
    }

    /**
     * Reads at most <tt>maxBytes</tt> bytes from the supplied input stream and
     * returns them as a byte array.
     *
     * @param in       The InputStream supplying the bytes.
     * @param maxBytes The maximum number of bytes to read from the input stream.
     * @return A byte array of size <tt>maxBytes</tt> if the input stream can
     *         produce that amount of bytes, or a smaller byte array containing
     *         all available bytes from the stream otherwise.
     */
    public static byte[] readBytes(InputStream in, int maxBytes) throws IOException {
        byte[] result = new byte[maxBytes];

        int bytesRead = readBytes(in, result);

        if (bytesRead < maxBytes) {
            // Create smaller byte array
            byte[] tmp = new byte[bytesRead];
            System.arraycopy(result, 0, tmp, 0, bytesRead);
            result = tmp;
        }

        return result;
    }

    /**
     * Fills the supplied byte array with bytes read from the specified
     * InputStream. This method will only stop reading when the byte array has
     * been filled completely, or the end of the stream has been reached.
     *
     * @param in        The InputStream to read the bytes from.
     * @param byteArray The byte array to fill with bytes.
     * @return The number of bytes written to the byte array.
     */
    public static int readBytes(InputStream in, byte[] byteArray) throws IOException {
        int totalBytesRead = 0;

        int bytesRead = in.read(byteArray);

        while (bytesRead >= 0) {
            totalBytesRead += bytesRead;

            if (totalBytesRead == byteArray.length) {
                break;
            }

            bytesRead = in.read(byteArray, totalBytesRead, byteArray.length - totalBytesRead);
        }

        return totalBytesRead;
    }

    /**
     * Transfers all bytes that can be read from <tt>in</tt> to <tt>out</tt>.
     *
     * @param in  The InputStream to read data from.
     * @param out The OutputStream to write data to.
     * @return The total number of bytes transfered.
     */
    public static final long transfer(InputStream in, OutputStream out) throws IOException {
        long totalBytes = 0;
        int bytesInBuf = 0;
        byte[] buf = new byte[4096];

        while ((bytesInBuf = in.read(buf)) != -1) {
            out.write(buf, 0, bytesInBuf);
            totalBytes += bytesInBuf;
        }

        return totalBytes;
    }

    /**
     * Writes all bytes from an <tt>InputStream</tt> to a file.
     *
     * @param in   The <tt>InputStream</tt> containing the data to write to the file.
     * @param file The file to write the data to.
     * @return The total number of bytes written.
     * @throws IOException If an I/O error occured while trying to write the data to the
     *                     file.
     */
    public static final long transfer(InputStream in, File file) throws IOException {
        FileOutputStream out = new FileOutputStream(file);

        try {
            return transfer(in, out);
        } finally {
            out.close();
        }
    }

    /**
     * Transfers all characters that can be read from <tt>in</tt> to <tt>out</tt>
     * .
     *
     * @param in  The Reader to read characters from.
     * @param out The Writer to write characters to.
     * @return The total number of characters transfered.
     */
    public static final long transfer(Reader in, Writer out) throws IOException {
        long totalChars = 0;
        int charsInBuf = 0;
        char[] buf = new char[4096];

        while ((charsInBuf = in.read(buf)) != -1) {
            out.write(buf, 0, charsInBuf);
            totalChars += charsInBuf;
        }

        return totalChars;
    }

    /**
     * Writes all characters from a <tt>Reader</tt> to a file using the default
     * character encoding.
     *
     * @param reader The <tt>Reader</tt> containing the data to write to the file.
     * @param file   The file to write the data to.
     * @return The total number of characters written.
     * @throws IOException If an I/O error occured while trying to write the data to the
     *                     file.
     * @see java.io.FileWriter
     */
    public static final long transfer(Reader reader, File file) throws IOException {
        FileWriter writer = new FileWriter(file);

        try {
            return transfer(reader, writer);
        } finally {
            writer.close();
        }
    }
}

Related

  1. readBytes(InputStream in, boolean forceClose)
  2. readBytes(InputStream in, byte[] b)
  3. readBytes(InputStream in, byte[] buf, int length)
  4. readBytes(InputStream in, byte[] buffer)