/********************************************************************* Copyright 2015 the Flapi authors 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. ********************************************************************/ package unquietcode.tools.flapi.examples.pipes; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; /** * @author Sun Microsystems * * from sun.misc */ public class IOUtils { /** * Read up to <code>length</code> of bytes from <code>in</code> * until EOF is detected. * @param is input stream, must not be null * @param length number of bytes to read, -1 or Integer.MAX_VALUE means * read as much as possible * @param readAll if true, an EOFException will be thrown if not enough * bytes are read. Ignored when length is -1 or Integer.MAX_VALUE * @return bytes read * @throws IOException Any IO error or a premature EOF is detected */ public static byte[] readFully(InputStream is, int length, boolean readAll) throws IOException { byte[] output = {}; if (length == -1) length = Integer.MAX_VALUE; int pos = 0; while (pos < length) { int bytesToRead; if (pos >= output.length) { // Only expand when there's no room bytesToRead = Math.min(length - pos, output.length + 1024); if (output.length < pos + bytesToRead) { output = Arrays.copyOf(output, pos + bytesToRead); } } else { bytesToRead = output.length - pos; } int cc = is.read(output, pos, bytesToRead); if (cc < 0) { if (readAll && length != Integer.MAX_VALUE) { throw new EOFException("Detect premature EOF"); } else { if (output.length != pos) { output = Arrays.copyOf(output, pos); } break; } } pos += cc; } return output; } }