以下是将InputStream转换为String的示例Java程序。在这里,我们尝试将ByteArrayInputStream的内容转换为字符串。
import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.Scanner; public class InputStreamToString { public static void main(String args[]) throws Exception{ System.out.println("Enter a string ::"); Scanner sc = new Scanner(System.in); byte[] data = sc.next().getBytes(); int size = data.length; byte[] b = new byte[size]; InputStream Inputstream = new ByteArrayInputStream(data); Inputstream.read(b); String str = new String(b); System.out.println(str); } }
输出结果
Enter a string :: Nhooo Nhooo