Java InputStream to OutputStream copyStream(InputStream in, OutputStream os)

Here you can find the source of copyStream(InputStream in, OutputStream os)

Description

Simple copy a stream with a buffer of 1024 bytes into an outputstream.

License

Apache License

Parameter

Parameter Description
in a parameter
os a parameter

Exception

Parameter Description
IOException an exception

Return

a String representation of copied bytes, null if outputstream is not a ByteArrayOutputStream.

Declaration

public static String copyStream(InputStream in, OutputStream os) throws IOException 

Method Source Code

//package com.java2s;
/**/*  w ww.  j  a  va 2 s. co m*/
 * Copyright (c) 2015-2017 Inria
 * <p>
 * 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
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * 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.
 * <p>
 * Contributors:
 * - Christophe Gourdin <christophe.gourdin@inria.fr>
 */

import java.io.*;

public class Main {
    /**
     * Simple copy a stream with a buffer of 1024 bytes into an outputstream.
     *
     * @param in
     * @param os
     * @return a String representation of copied bytes, null if outputstream is
     * not a ByteArrayOutputStream.
     * @throws IOException
     */
    public static String copyStream(InputStream in, OutputStream os) throws IOException {
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            os.write(buf, 0, len);
        }
        os.flush();
        if (os instanceof ByteArrayOutputStream) {
            return new String(((ByteArrayOutputStream) os).toByteArray(), "UTF-8");
        }
        return null;
    }
}

Related

  1. copyStream(InputStream from, OutputStream to)
  2. copyStream(InputStream in, boolean closeIn, OutputStream out, boolean closeOut)
  3. copyStream(InputStream in, File outputFile)
  4. copyStream(InputStream in, FileOutputStream out, IProgressMonitor monitor, int length)
  5. copyStream(InputStream in, OutputStream os)
  6. copyStream(InputStream in, OutputStream out)
  7. copyStream(InputStream in, OutputStream out)
  8. copyStream(InputStream in, OutputStream out)
  9. copyStream(InputStream in, OutputStream out)