How to convert InputStream to String in Java?
Published: August 23, 2010 , Updated: August 23, 2010 , Author: mkyong
To convert InputStream to String, you can use the BufferedReader to read the InputStream and return a String.
Example
package com.mkyong; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class InputStreamToStringExample { public static void main(String[] args) throws IOException { //intilize an InputStream InputStream is = new ByteArrayInputStream("file content".getBytes()); //read it with BufferedReader BufferedReader br = new BufferedReader( new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line); } System.out.println(sb.toString()); br.close(); } }
Any Java questions or problems? please post at this JavaNullPointer.com forum, see you there ~
There’s a much better trick that doesn’t require apache stuff.
Essentially this tells the scanner to tokenize the stream until the end is reached, so next() returns the whole stream as a string.
I prefer to use IOUtils.toString(InputStream) from Apache Commons.