Java InputStream to OutputStream copyStream(InputStream input, OutputStream output, boolean closeStreams)

Here you can find the source of copyStream(InputStream input, OutputStream output, boolean closeStreams)

Description

Copies one stream to another, optionally closing the streams.

License

Apache License

Parameter

Parameter Description
input the data to copy
output where to copy the data
closeStreams if true input and output will be closed when the method returns

Exception

Parameter Description
RuntimeException if the copy failed

Return

the number of bytes copied

Declaration

public static long copyStream(InputStream input, OutputStream output, boolean closeStreams)
        throws RuntimeException 

Method Source Code


//package com.java2s;
/*/*from w w  w . j  av a2s .  c om*/
 * Copyright 2015-2016 Red Hat, Inc. and/or its affiliates
 * and other contributors as indicated by the @author tags.
 *
 * 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.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;

import java.io.Writer;

public class Main {
    private static final String ENCODING_UTF_8 = "utf-8";
    private static final int BUFFER_SIZE = 128;

    /**
     * Copies one stream to another, optionally closing the streams.
     *
     * @param input the data to copy
     * @param output where to copy the data
     * @param closeStreams if true input and output will be closed when the method returns
     * @return the number of bytes copied
     * @throws RuntimeException if the copy failed
     */
    public static long copyStream(InputStream input, OutputStream output, boolean closeStreams)
            throws RuntimeException {
        long numBytesCopied = 0;
        int bufferSize = BUFFER_SIZE;
        try {
            // make sure we buffer the input
            input = new BufferedInputStream(input, bufferSize);
            byte[] buffer = new byte[bufferSize];
            for (int bytesRead = input.read(buffer); bytesRead != -1; bytesRead = input.read(buffer)) {
                output.write(buffer, 0, bytesRead);
                numBytesCopied += bytesRead;
            }
            output.flush();
        } catch (IOException ioe) {
            throw new RuntimeException("Stream data cannot be copied", ioe);
        } finally {
            if (closeStreams) {
                try {
                    output.close();
                } catch (IOException ioe2) {
                    // what to do?
                }
                try {
                    input.close();
                } catch (IOException ioe2) {
                    // what to do?
                }
            }
        }
        return numBytesCopied;
    }

    /**
     * Read the content of the given {@code file} using {@link #ENCODING_UTF_8} and return it as a {@link String}.
     * @param file the {@link File} to read from
     * @return the content of the given {@code file}
     * @throws IOException in IO problems
     */
    public static String read(File file) throws IOException {
        return slurpStream(new FileInputStream(file), ENCODING_UTF_8);
    }

    /**
     * Stores {@code string} to {@code file} using {@link #ENCODING_UTF_8}.
     *
     * @param string the {@link String} to store
     * @param file the file to store to
     * @throws IOException on IO errors
     */
    public static void write(String string, File file) throws IOException {
        try (Writer w = new OutputStreamWriter(new FileOutputStream(file), ENCODING_UTF_8)) {
            w.write(string);
        }
    }

    /**
     * Given an input stream, its data will be slurped in memory and returned as a String. The input stream will be
     * closed when this method returns. WARNING: do not slurp large streams to avoid out-of-memory errors.
     *
     * @param input the input stream to slup
     * @param the encoding to use when reading from {@code input}
     * @return the input stream data as a String
     * @throws IOException in IO problems
     */
    public static String slurpStream(InputStream input, String encoding) throws IOException {
        try (Reader r = new InputStreamReader(input, encoding)) {
            StringBuilder result = new StringBuilder();
            char[] buffer = new char[BUFFER_SIZE];
            int len = 0;
            while ((len = r.read(buffer, 0, BUFFER_SIZE)) >= 0) {
                result.append(buffer, 0, len);
            }
            return result.toString();
        }
    }
}

Related

  1. copyStream(InputStream input, OutputStream output)
  2. copyStream(InputStream input, OutputStream output)
  3. copyStream(InputStream input, OutputStream output)
  4. copyStream(InputStream input, OutputStream output)
  5. copyStream(InputStream input, OutputStream output, boolean closeStreams)
  6. copyStream(InputStream input, OutputStream output, int bufferSize)
  7. copyStream(InputStream input, OutputStream output, int length)
  8. copyStream(InputStream inputStream, OutputStream outputStream)
  9. copyStream(InputStream inputStream, OutputStream outputStream)