Java Language Converting to and from Strings Getting a `String` from an `InputStream`

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

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"));


Got any Java Language Question?