Java教程

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

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

在这个程序中,我们将学习在 Java 中将字符串转换为输入流。
要理解此示例,您应该了解以下Java 编程主题:
Java 字符串 Java InputStream 类 Java ByteArrayInputStream 类

示例: 将字符串转换为 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()
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4