如何在 Java 中将字符串转换为 InputStream 对象?\
javaobject oriented programmingprogramming更新于 2025/6/2 7:40:17
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 TutorialsPoint";
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 TutorialsPoint
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

