Java InputStream 类

java.io包中的InputStream类是一个抽象超类,它表示一个字节输入流。

由于InputStream是一个抽象类,它本身没有实际用途。但是,它的子类可以用来读取数据。


InputStream的子类

为了使用InputStream的功能,我们可以使用它的子类。其中一些是:

FileInputStream class inherits the InputStream class
Java FileInputStream类

我们将在下一个教程中学习所有这些子类。


创建InputStream

要创建InputStream,我们必须首先导入java.io.InputStream包。导入包后,我们可以这样创建输入流。

// Creates an InputStream
InputStream object1 = new FileInputStream();

在这里,我们使用FileInputStream创建了一个输入流。这是因为InputStream是一个抽象类。因此,我们无法创建InputStream的对象。


InputStream的方法

InputStream类提供了由其子类实现的不同方法。以下是一些常用的方法:

  • read() - 从输入流中读取一个字节的数据
  • read(byte[] array) - 从流中读取字节并存储在指定的数组
  • available() - 返回输入流中可用的字节数
  • mark() - 标记输入流中已读取数据的点
  • reset() - 将控件返回到流中设置标记的点
  • markSupported() - 检查流是否支持mark()reset()方法
  • skips() - 跳过并丢弃输入流中的指定字节数
  • close() - 关闭输入流

示例:使用FileInputStream的InputStream

以下是使用FileInputStream类实现InputStream的方法。

假设我们有一个名为input.txt的文件,内容如下:

This is a line of text inside the file.

让我们尝试使用FileInputStreamInputStream的子类)读取此文件。

import java.io.FileInputStream;
import java.io.InputStream;

class Main {
  public static void main(String args[]) {

    byte[] array = new byte[100];

    try {
      InputStream input = new FileInputStream("input.txt");

      System.out.println("Available bytes in the file: " + input.available());

      // Read byte from the input stream
      input.read(array);
      System.out.println("Data read from the file: ");

      // Convert byte array into string
      String data = new String(array);
      System.out.println(data);

      // Close the input stream
      input.close();
    } catch (Exception e) {
      e.getStackTrace();
    }
  }
}

输出

Available bytes in the file: 39
Data read from the file:
This is a line of text inside the file

在上面的示例中,我们使用FileInputStream类创建了一个输入流。该输入流与input.txt文件链接。

InputStream input = new FileInputStream("input.txt");

为了从input.txt文件读取数据,我们实现了以下两个方法:

input.read(array);  // to read data from the input stream
input.close();            // to close the input stream

要了解更多信息,请访问Java InputStream(官方Java文档)

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

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

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

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