Read data from is until the buffer is full or the stream is closed. - Java java.io

Java examples for java.io:InputStream Read

Description

Read data from is until the buffer is full or the stream is closed.

Demo Code

/*/*from  w ww. j a v a 2s. c  o m*/
 * silvertunnel.org Netlib - Java library to easily access anonymity networks
 * Copyright (c) 2009-2012 silvertunnel.org
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, see <http://www.gnu.org/licenses/>.
 */
//package com.java2s;
import java.io.IOException;
import java.io.InputStream;

public class Main {
    /**
     * Read data from is until the buffer is full or the stream is closed.
     * 
     * @param maxResultSize
     * @param is
     * @return the bytes read (length<=maxResultSize).
     */
    public static byte[] readDataFromInputStream(int maxResultSize,
            InputStream is) throws IOException {
        byte[] tempResultBuffer = new byte[maxResultSize];

        int len = 0;
        do {
            if (len >= tempResultBuffer.length) {
                //log.info("result buffer is full");
                break;
            }
            int lastLen = is.read(tempResultBuffer, len,
                    tempResultBuffer.length - len);
            if (lastLen < 0) {
                //log.info("end of result stream");
                break;
            }
            len += lastLen;
        } while (true);

        // copy to result buffer
        byte[] result = new byte[len];
        System.arraycopy(tempResultBuffer, 0, result, 0, len);

        return result;
    }
}

Related Tutorials