Java InputStream read String up to max Length bytes

Description

Java InputStream read String up to max Length bytes


//package com.demo2s;

import java.io.IOException;
import java.io.InputStream;

import java.io.StringWriter;

public class Main {
 

    /**// w  w  w .j  a v  a2 s  . c  om
     * Read a String of up to maxLength bytes from an InputStream
     *
     * @param is input stream
     * @param maxLength max number of bytes to read from "is". If this is -1, we
     *          read everything.
     *
     * @return String up to maxLength bytes, read from "is"
     */
    public static String stream2String(InputStream is, int maxLength) throws IOException {
        byte[] buffer = new byte[4096];
        StringWriter sw = new StringWriter();
        int totalRead = 0;
        int read = 0;

        do {
            sw.write(new String(buffer, 0, read));
            totalRead += read;
            read = is.read(buffer, 0, buffer.length);
        } while (((-1 == maxLength) || (totalRead < maxLength)) && (read != -1));

        return sw.toString();
    }

}



PreviousNext

Related