English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
在此程序中,您将学习如何使用Java中的InputStreamReader将输入流(InputStream)转换为字符串。
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 haveIOException is thrown:
public static void main(String[] args) throws IOException