Here you can find the source of copyBytesToStream(InputStream inputStream, OutputStream outputStream, int length)
Parameter | Description |
---|---|
IOException | if it fails to read given length amount of elements. |
public static void copyBytesToStream(InputStream inputStream, OutputStream outputStream, int length) throws IOException
//package com.java2s; /******************************************************************************* * Copyright (c) 2007, 2014 Bruno Medeiros and other Contributors. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors:/*from w ww . java 2s .c o m*/ * Bruno Medeiros - initial implementation *******************************************************************************/ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class Main { /** Copies given length amount of bytes from given inputStream to given outputStream. * Alternatively, if length == -1, copy all bytes in inputStream until EOF. * @throws IOException if it fails to read given length amount of elements. */ public static void copyBytesToStream(InputStream inputStream, OutputStream outputStream, int length) throws IOException { final int BUFFER_SIZE = 1024; byte[] buffer = new byte[BUFFER_SIZE]; int totalRead = 0; do { int readReqLen = (length == -1) ? BUFFER_SIZE : Math.min(BUFFER_SIZE, length - totalRead); int read = inputStream.read(buffer, 0, readReqLen); if (read == -1) { if (length != -1) { throw createFailedToReadExpected(length, totalRead); } else { return; // Nothing more to copy. } } totalRead += read; outputStream.write(buffer, 0, read); } while (totalRead != length); } private static IOException createFailedToReadExpected(int length, int totalRead) { return new IOException("Failed to read requested amount of characters. " + "Read: " + totalRead + " of total requested: " + length); } }