Last Updated: September 12, 2021
·
120
· Bruno Volpato

Read InputStream into String

Turn an arbitrary InputStream into a String using buffered read.

public static final int BUFFER_SIZE = 8192;

public static String readContent(InputStream in) throws IOException {
  final byte[] readBuffer = new byte[BUFFER_SIZE];

  StringBuilder sb = new StringBuilder();
  try {
    if (in.available() > 0) {
      int bytesRead = 0;
      while ((bytesRead = in.read(readBuffer)) != -1) {
        sb.append(new String(readBuffer, 0, bytesRead));
      }
    }
  } catch (IOException e) {
    throw e;
  } finally {
    try {
      in.close();
    } catch (IOException e) {
      throw e;
    }
  }

  return sb.toString();
}