Java 将字符串转换为InputStream
在显示长字符串时,我们有时需要将其分为较小的单元进行处理。此时,将字符串转换为InputStream将会很有帮助。为了将给定的字符串转换为InputStream,Java提供了ByteArrayInputStream类,该类与一个名为getBytes()的内置方法一起使用。在本文中,我们将学习如何使用ByteArrayInputStream类通过示例程序将字符串转换为InputStream。
将字符串转换为InputStream的Java程序
本节将介绍一些概念,这些概念将帮助我们理解用于字符串到InputStream转换的Java程序。
InputStream
流是在Java中执行输入和输出操作时使用的抽象。流有两个基本术语,即InputStream类用于从键盘、磁盘文件等源获取输入,OutputStream类用于指向显示或写入数据的目标。
BufferedReader类
由于InputStream类是一个抽象类,我们需要使用它的子类来实现其功能。其中一个子类是BufferedReader,它用于从本地文件和键盘等输入流中读取字符。要使用BufferedReader读取字符串,我们需要创建一个InputStream类的实例,并将其作为参数传递给BufferedReader的构造函数。
语法
BufferedReader nameOfObject = new BufferedReader(objectOfStream);
getBytes() 方法
它是String类的内置方法,用于将字符串编码为字节数组。它可以接受一个可选参数来指定字符编码。如果我们不传递任何字符集,它将使用默认的字符集。
此外,我们将把这个字节数组作为参数传递给ByteArrayInputStream,并将其赋值给InputStream类的实例,这样我们就可以将字符串转换为InputStream。
示例1
以下Java程序演示了如何将字符串转换为InputStream。
方法
- 首先,初始化一个字符串。
-
然后,使用getBytes()方法以及ByteArrayInputStream类将指定的字符串转换为具有默认字符集的字节数组,并将该数组赋值给InputStream。
-
接下来,使用BufferedReader类来读取流。
-
最后,使用一个while循环,直到流的内容不等于’null’时,打印流。
import java.io.*;
public class Example1 {
public static void main(String[] args) throws IOException {
try {
// initializing a string
String inputString = "Hello! this is Tutorials Point!!";
// converting the string to InputStream
InputStream streamIn = new ByteArrayInputStream(inputString.getBytes());
// creating instance of BufferedReader
BufferedReader bufrd = new BufferedReader(new InputStreamReader(streamIn));
// New string to store the original string
String info = null;
// loop to print the result
while ((info = bufrd.readLine()) != null) {
System.out.println(info);
}
} catch(Exception exp) { // to handle the exception if occurred
System.out.println(exp);
}
}
}
输出
Hello! this is Tutorials Point!!
示例2
如前所述,我们可以传递一个可选参数来指定字节数组的字符编码。在下面的Java程序中,我们将把’UTF-8’作为一个参数传递给getBytes()方法。
import java.io.*;
public class Example2 {
public static void main(String[] args) throws IOException {
// initializing a string
String inputString = "Hello! this is Tutorials Point!!";
// converting the string to InputStream
InputStream streamIn = new ByteArrayInputStream(inputString.getBytes("UTF-8"));
// creating instance of BufferedReader
BufferedReader bufrd = new BufferedReader(new InputStreamReader(streamIn));
// New string to store the original string
String info = null;
// loop to print the result
while ((info = bufrd.readLine()) != null) {
System.out.println(info);
}
}
}
输出
Hello! this is Tutorials Point!!
结论
在本文中,我们学习了如何在Java中将给定的字符串转换为InputStream。为了实现这个目的,我们讨论了两个利用ByteArrayInputStream类,BufferedReader类和getBytes()方法的Java程序。使用getBytes()方法和ByteArrayInputStream,我们能够将字符串转换为整数,并借助BufferedReader类读取该流。