示例: 将输出流转换为字符串
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()
方法。