English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn how to use InputStreamReader in Java to convert an InputStream to a string.
import java.io;*; public class InputStreamString { public static void main(String[] args) throws IOException { InputStream stream = new ByteArrayInputStream("Hello there!".getBytes()); StringBuilder sb = new StringBuilder(); String line; BufferedReader br = new BufferedReader(new InputStreamReader(stream)); while ((line = br.readLine()) != null) { sb.append(line); } br.close(); System.out.println(sb); } }
When the program is run, the output is:
Hello there!
In the above program, the input stream is created from String and stored in the variable stream. We also need a string builder sb to create a string from the stream.
Then, we create a buffered reader br from InputStreamReader to read lines from the stream. Using a while loop, we read each line and append it to the string builder. Finally, we close the bufferedReader.
Because the reader can throw IOException, we have in the main functionIOException is thrown:
public static void main(String[] args) throws IOException