将字符串转换为 InputStream 的 Java 程序

要理解此示例,您应该具备以下 Java 编程的知识:

示例:将 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 = "HelloWorld";
    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: HelloWorld
InputStream: [email protected]
Available bytes at the beginning: 9
Available bytes at the end: 6

在上面的例子中,我们创建了一个名为 name 的字符串. 在这里,我们将字符串转换为名为 stream 的输入流.

getBytes() 方法将字符串转换为字节。要了解更多信息,请访问 Java String getBytes()