Java ByteArrayOutputStream Write readAllAndKeepOpen(InputStream bytes, int bufferSize)

Here you can find the source of readAllAndKeepOpen(InputStream bytes, int bufferSize)

Description

Read all of the bytes in an input stream.

License

Apache License

Parameter

Parameter Description
bytes the InputStream of bytes to read
bufferSize the number of bytes to buffer at each read

Exception

Parameter Description
IOException if the stream fails

Return

an array of all bytes retrieved from the stream

Declaration

public static byte[] readAllAndKeepOpen(InputStream bytes, int bufferSize) throws IOException 

Method Source Code


//package com.java2s;
/*/*from  w  ww.ja  v  a2 s  .  co m*/
 * Copyright (c) 2017 Intel Corporation 
 *
 * 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.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class Main {
    /**
     * Read all of the bytes in an input stream. Note that this will close the passed stream after all bytes have been
     * read.
     *
     * @param bytes the {@link InputStream} of bytes to read
     * @param bufferSize the number of bytes to buffer at each read
     * @return an array of all bytes retrieved from the stream
     * @throws IOException if the stream fails
     */
    public static byte[] readAllAndKeepOpen(InputStream bytes, int bufferSize) throws IOException {
        try (ByteArrayOutputStream builder = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[bufferSize];
            int read;
            while ((read = bytes.read(buffer)) != -1) {
                builder.write(buffer, 0, read);
            }
            return builder.toByteArray();
        }
    }
}

Related

  1. readAll(InputStream inputStream)
  2. readAll(InputStream is)
  3. readAll(InputStream s)
  4. readAll(InputStream stream)
  5. readAllAndClose(InputStream is)
  6. readAllBinary(InputStream stream)
  7. readAllFrom(InputStream in, boolean chunked)
  8. readAllFromFile(File f)
  9. readAllFromFile(String file)