java将String转换为InputStream,stringinputstream,下面代码演示如何将字符串
分享于 点击 10872 次 点评:227
java将String转换为InputStream,stringinputstream,下面代码演示如何将字符串
下面代码演示如何将字符串转换为InputStream并从中读取字符串。
我们使用ByteArrayInputStream类来创建流对象,并将String.getBytes(str)放回的字节数组作为参数传给其构造函数。
InputStream初始化之后我们逐个字符的读取其内容,并打印到控制台
package cn.outofmemory.examples;import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.InputStream;import java.io.UnsupportedEncodingException;/** * * @author byrx.net */public class Main { public static void main(String[] args) { String text = "Example on how to convert a String to an InputStream"; try { InputStream is = new ByteArrayInputStream(text.getBytes()); int byteRead; while ((byteRead = is.read()) != -1) { System.out.print((char)byteRead); } System.out.println(); is.close(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }}
上面程序输出:
Converting String to InputStream Example
用户点评