Java 程序:将 String 转换为 InputStream

要理解此示例,您应了解以下Java编程主题


示例:Java 程序将 String 转换为 InputStream

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()

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战