Java FileInputStream Read readFile(final InputStream stream)

Here you can find the source of readFile(final InputStream stream)

Description

Reads data from a stream.

License

Open Source License

Parameter

Parameter Description
stream The stream from which to read the data.

Exception

Parameter Description
IOException When read fails.

Return

data The read data.

Declaration

public static byte[] readFile(final InputStream stream) throws IOException 

Method Source Code


//package com.java2s;
/*/*w ww .j  a va  2s. c o  m*/
 * Copyright (C) 2011 Klaus Reimer <k@ailis.de>
 * See LICENSE.md for licensing information.
 */

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;

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

public class Main {
    /**
     * Reads data from a file.
     *
     * @param filename
     *            The filename. Can be '-' for reading from stdin.
     * @return data The read data.
     * @throws IOException
     *             When read fails.
     */
    public static byte[] readFile(final String filename) throws IOException {
        if (filename.equals("-"))
            return readFile(System.in);

        try (final InputStream stream = new FileInputStream(filename)) {
            return readFile(stream);
        }
    }

    /**
     * Reads data from a stream.
     *
     * @param stream
     *            The stream from which to read the data.
     * @return data The read data.
     * @throws IOException
     *             When read fails.
     */
    public static byte[] readFile(final InputStream stream) throws IOException {
        final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        copy(stream, bytes);
        return bytes.toByteArray();
    }

    /**
     * Copies data from input stream to output stream.
     *
     * @param input
     *            The input stream
     * @param output
     *            The output stream
     * @throws IOException
     *             When copying fails.
     */
    public static void copy(final InputStream input, final OutputStream output) throws IOException {
        final byte[] buffer = new byte[8192];
        int read;
        while ((read = input.read(buffer)) != -1) {
            output.write(buffer, 0, read);
        }
    }
}

Related

  1. readFile(File target)
  2. readFile(FileInputStream fileinputstream, byte abyte0[])
  3. readFile(final File file)
  4. readFile(final File file)
  5. readFile(final File file)
  6. readFile(final String fileNamePath)
  7. readFile(InputStream ios)
  8. readFile(InputStream iStream)
  9. readFile(String destination)