Here you can find the source of copyStream(InputStream input, OutputStream output, boolean closeStreams)
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 |
Parameter | Description |
---|---|
RuntimeException | if the copy failed |
public static long copyStream(InputStream input, OutputStream output, boolean closeStreams) throws RuntimeException
//package com.java2s; /*/*from ww w .j a v a 2 s . c o m*/ * Copyright 2015 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.IOException; import java.io.InputStream; import java.io.OutputStream; public class Main { /** * 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 = 32768; 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; } }