如何在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 教师闺蜜祝福语简短