Java程序:将字符串转换为InputStream
要将给定的字符串转换为InputStream,Java提供了ByteArrayInputStream类,它与名为getBytes()的内置方法一起使用。在显示较长的输入字符串时,有时需要以较小的单元处理它们。此时,将该字符串转换为InputStream将很有帮助。
在本文中,我们将学习如何使用ByteArrayInputStream类结合示例程序将字符串转换为InputStream。在讨论之前,我们需要先学习一些概念:
InputStream
流有两个基本类,即InputStream类,用于从键盘、磁盘文件等来源获取输入;以及OutputStream类,用于将数据显示或写入目标。这里,术语Stream(流)是执行Java中的输入和输出操作时使用的抽象。
BufferedReader类
由于InputStream类是一个抽象类,我们需要使用它的子类来实现其功能。其中一个子类是BufferedReader,用于从输入流(如本地文件和键盘)读取字符。要使用BufferedReader读取字符串,我们需要创建InputStream类的实例,并将其作为参数传递给BufferedReader的构造函数。
getBytes()方法
它是String类的内置方法,用于将字符串编码为字节数组。它可以接受一个可选参数来指定字符编码。如果我们不传递任何字符集,它将使用默认字符集。
我们将此字节数组作为参数传递给ByteArrayInputStream,并将其分配给InputStream类的实例,以便我们可以将字符串转换为InputStream。
Java中的字符串到InputStream转换
让我们讨论一些Java程序,它们演示了字符串到InputStream的转换:
示例1
下面的Java程序演示了如何将字符串转换为InputStream。
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类,我们读取了该流。
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP