Java implements the input flow as String

  • 2020-05-26 08:35:15
  • OfStack

In the normal development of Java, it is inevitable to meet the demand of the input flow into String type. I often meet such demand when I am engaged in the development of Android, so I made this into a tool class and Shared it with you, hoping to help you. This is also the first time for me to write a personal blog, I hope you can support me. Thank you very much!


public static String streamToString(InputStream is) {
  BufferedReader reader = new BufferedReader(new InputStreamReader(is));
  //new1 a StringBuffer For string concatenation 
  StringBuffer sb = new StringBuffer();
  String line = null;
  try {
    // When the input stream content has been read 
    while ((line = reader.readLine()) != null) {
       sb.append(line + "\n");
    }
    // Remember to turn off the streaming data   Save memory consumption 
    is.close();
    reader.close();
    return sb.toString();
  } catch (IOException e) {
    e.printStackTrace();
  } 
  return null;
}

Related articles: