Question:
How to convert InputStream to String in Java?
Code:
import java.io.*; public class InputStreamToString { public static void main(String[] args) throws IOException { String str = "Do you like green eggs and ham. I do not like them, Sam I am."; InputStream is = new ByteArrayInputStream(str.getBytes()); String result = getStringFromInputStream(is); System.out.println(result); } private static String getStringFromInputStream(InputStream is) { BufferedReader br = null; StringBuilder sb = new StringBuilder(); String line; try { br = new BufferedReader(new InputStreamReader(is)); while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } return sb.toString(); } }
Output:
$ java InputStreamToString Do you like green eggs and ham. I do not like them, Sam I am.