如何在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 婚前女儿生日祝福语简短