Here you can find the source of inputStreamToString(InputStream input, Charset charset, boolean closeInputAfterRead)
Parameter | Description |
---|---|
input | the input stream |
charset | charset set |
closeInputAfterRead | true to close input stream after use false to leave it unclosed. |
Parameter | Description |
---|---|
IOException | an exception |
public static String inputStreamToString(InputStream input, Charset charset, boolean closeInputAfterRead) throws IOException
//package com.java2s; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.nio.charset.Charset; public class Main { /**//from ww w. j ava2 s . c om * Reads the input stream till the end and return the reading as a string. * @param input the input stream * @param charset charset set * @param closeInputAfterRead true to close input stream after use false to leave it unclosed. * @return the read string * @throws IOException */ public static String inputStreamToString(InputStream input, Charset charset, boolean closeInputAfterRead) throws IOException { StringBuilder sb = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(input, charset)); String line = null; while ((line = reader.readLine()) != null) { if (sb.length() > 0) { sb.append("\n"); } sb.append(line); } if (closeInputAfterRead) { input.close(); } return sb.toString(); } /** * Closes a Writer without throwing any exception if something went wrong. * @param device output writer, can be null. */ public static void close(Writer device) { if (null != device) { try { device.close(); } catch (IOException e) { //ignore } } } /** * Close a Reader without throwing any exception if something went wrong. * @param device Reader, can be null. */ public static void close(Reader device) { if (null != device) { try { device.close(); } catch (IOException e) { //ignore } } } /** * Close a stream without throwing any exception if something went wrong. * @param device stream, can be null. */ public static void close(OutputStream device) { if (null != device) { try { device.close(); } catch (IOException e) { //ignore } } } /** * Close a stream without throwing any exception if something went wrong. * @param device stream, can be null. */ public static void close(InputStream device) { if (null != device) { try { device.close(); } catch (IOException e) { //ignore } } } }