示例:将 OutputStream 转换为 String
import java.io.*;
public class OutputStreamString {
public static void main(String[] args) throws IOException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
String line = "Hello there!";
stream.write(line.getBytes());
String finalString = new String(stream.toByteArray());
System.out.println(finalString);
}
}
输出
Hello there!
在上面的程序中,我们根据给定的字符串 line 创建了一个 OutputStream
。这是使用流的 write()
方法完成的。
然后,我们使用 String
的采用字节数组作为参数的构造函数,将 OutputStream
转换为 finalString。为此,我们使用流的 toByteArray()
方法。