如何在Java中将字符串转换为InputStream对象?
甲ByteArrayInputStream的 是的一个子类的InputStream 类,它包含一个包含一个内部缓冲器字节 可从流中读取。我们可以使用ByteArrayInputStream 类将String转换为InputStream对象。此类的构造函数采用字符串字节数组,这可以通过调用String类的getBytes() 方法来完成。
示例
import java.io.*;
public class StringToInputStreamTest {
public static void main(String []args) throws Exception {
String str = "Welcome to nhooo";
InputStream input = getInputStream(str, "UTF-8");
int i;
while ((i = input.read()) > -1) {
System.out.print((char) i);
}
System.out.println();
}
public static InputStream getInputStream(String str, String encoding) throws UnsupportedEncodingException {
return new ByteArrayInputStream(str.getBytes(encoding));
}
}输出结果
Welcome to nhooo
热门推荐
10 部队牛年祝福语简短的
11 天仓节祝福语简短
12 女神节祝福语简短创意
13 感谢室友结婚祝福语简短
14 虎年幽默搞笑简短祝福语
15 弟媳离职回家祝福语简短
16 英文节日祝福语简短唯美
17 给弟弟敬茶祝福语简短
18 圣诞祝福语简短贺卡英文