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); } }
Quando si esegue il programma, l'output è:
Ciao lì!
Nel programma sopra, lo stream di input è stato creato da String e memorizzato nella variabile stream. Abbiamo anche bisogno di un costruttore di stringa sb per creare una stringa dallo stream.
Poi, creiamo un lettore di buffer br da InputStreamReader per leggere le righe dallo stream. Utilizzando un ciclo while, leggiamo ogni riga e la aggiungiamo al costruttore di stringa. Infine, chiudiamo bufferedReader.
Poiché il lettore può lanciare IOException, quindi nel nostro main abbiamoIOException lanciata:
public static void main(String[] args) throws IOException