Java Language Getting a `String` from an `InputStream`


Example

A String can be read from an InputStream using the byte array constructor.

import java.io.*;

public String readString(InputStream input) throws IOException {
    byte[] bytes = new byte[50]; // supply the length of the string in bytes here
    input.read(bytes);
    return new String(bytes);
}

This uses the system default charset, although an alternate charset may be specified:

return new String(bytes, Charset.forName("UTF-8"));