在此程序中,您將學(xué)習(xí)如何使用Java中的InputStreamReader將輸入流(InputStream)轉(zhuǎn)換為字符串。
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);
}
}運(yùn)行程序時,輸出為:
Hello there!
在上述程序中,輸入流是從String創(chuàng)建的,并存儲在變量stream中。 我們還需要一個字符串生成器sb來從流中創(chuàng)建字符串。
然后,我們從InputStreamReader創(chuàng)建一個緩沖讀取器br來讀取stream中的行。使用while循環(huán),我們讀取每一行并將其附加到字符串構(gòu)建器中。最后,我們關(guān)閉了bufferedReader。
因?yàn)殚喿x器可以拋出IOException,所以我們在主函數(shù)中具有IOException拋出:
public static void main(String[] args) throws IOException