Proper way to read InputStream to byte array

There are many ways to accomplish this but this one does not use any external dependencies like Apache commons.

Two common pitfalls that I see are that people forget to flush the ByteArrayOutputStream and they call ‘baos.write(buffer)’ instead of ‘baos.write(buffer, 0, read)’ without actually clearing the buffer, which causes the last write to append previous bytes if the read returned less than what has been read from the input stream.

	private String extract(InputStream inputStream) throws IOException {	
		ByteArrayOutputStream baos = new ByteArrayOutputStream();				
		byte[] buffer = new byte[1024];
		int read = 0;
		while ((read =, 0, buffer.length)) != -1) {
			baos.write(buffer, 0, read);
		return  new String(baos.toByteArray(), "UTF-8");

9 thoughts on “Proper way to read InputStream to byte array”