示例:将String转换为InputStream的Java程序
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
public class Main {
public static void main(String args[]) {
// Creates a string
String name = "Programiz";
System.out.println("String is: " + name);
try {
InputStream stream = new ByteArrayInputStream(name.getBytes(StandardCharsets.UTF_8));
System.out.println("InputStream: " + stream);
// Returns the available number of bytes
System.out.println("Available bytes at the beginning: " + stream.available());
// Reads 3 bytes from the stream stream
stream.read();
stream.read();
stream.read();
// After reading 3 bytes
// Returns the available number of bytes
System.out.println("Available bytes at the end: " + stream.available());
stream.close();
}
catch (Exception e) {
e.getStackTrace();
}
}
}
输出
String is: Programiz
InputStream: java.io.ByteArrayInputStream@5479e3f
Available bytes at the beginning: 9
Available bytes at the end: 6
在上面的示例中,我们创建了一个名为name的字符串 。在这里,我们将字符串转换为名为stream的输入流 。
getBytes()
方法将字符串转换为字节。要了解更多信息,请访问Java String getBytes()