Home > Java > javaTutorial > body text

Java converts input stream into String

高洛峰
Release: 2017-01-11 14:03:47
Original
2146 people have browsed it

During normal Java development, it is inevitable to encounter the need to convert the input stream into String type. When I am engaged in Android development, I often encounter such needs, so I made this into a tool class to share with everyone, hoping to help everyone. This is also my first time writing a personal blog, I hope you all will support me. Thanks!

public static String streamToString(InputStream is) {
  BufferedReader reader = new BufferedReader(new InputStreamReader(is));
  //new一个StringBuffer用于字符串拼接
  StringBuffer sb = new StringBuffer();
  String line = null;
  try {
    //当输入流内容读取完毕时
    while ((line = reader.readLine()) != null) {
       sb.append(line + "\n");
    }
    //记得关闭流数据 节约内存消耗
    is.close();
    reader.close();
    return sb.toString();
  } catch (IOException e) {
    e.printStackTrace();
  } 
  return null;
}
Copy after login

The above is the Java implementation of converting input stream into String introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. I would also like to thank you all for your support of the PHP Chinese website!

For more articles related to Java's implementation of converting input streams into String, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!