English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Основной учебник Java

Java Управление потоком

Java Массивы

Java Ориентированность на объекты (I)

Java Ориентированность на объекты (II)

Java Ориентированность на объекты (III)

Обработка исключений Java

Java Список (List)

Java Queue (очередь)

Java Map集合

Java Set集合

Java Ввод/вывод (I/O)

Java Reader/Writer

Другие темы Java

Java InputStream класс

В этом уроке мы изучим пример Java InputStream класса и его методы.

Класс InputStream пакета java.io является абстрактной суперклассом, которая представляет собой поток ввода байтов.

Поскольку InputStream является абстрактным классом, сам по себе он не используется. Однако, его подклассы могут использоваться для чтения данных.

Подклассы InputStream

Чтобы использовать функции InputStream, мы можем использовать его подклассы. К ним относятся:

В следующем уроке мы изучим все эти подклассы.

Create an InputStream

To create an InputStream, we must first import the java.io.InputStream package. After importing the package, we can create an input stream.

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

Here, we create an input stream using FileInputStream. This is because InputStream is an abstract class. Therefore, we cannot create an InputStream object.

Note: We can also create input streams from other subclasses of InputStream.

InputStream methods

The InputStream class provides different methods implemented by its subclasses. Here are some commonly used methods

  • read() - Read one byte of data from the input stream

  • read(byte[] array) - Read bytes from the stream and store them in the specified array

  • available() - Return the number of bytes available in the input stream

  • mark() - Mark the position of the data in the input stream

  • reset() - Return the control point to the point set by mark() in the stream

  • markSupported() - Check if the stream supports mark() and reset() methods

  • skips() - Skip and discard the specified number of bytes from the input stream

  • close() - Close the input stream

Example: InputStream using FileInputStream

The following is the implementation of the InputStream method using FileInputStream class.

Assuming we have a file namedinput.txtThe file contains the following content.

Это строка текста в файле.

Let's try to use FileInputStream (a subclass of InputStream) to read this file.

import java.io.FileInputStream;
import java.io.InputStream;
public 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 bytes from the input stream
            input.read(array);
            System.out.println("Data read from file: ");
            //Convert a byte array to a string
            String data = new String(array);
            System.out.println(data);
            //Закрыть поток ввода
            input.close();
        }
        catch (Exception e) {
            e.getStackTrace();
        }
    }
}

Результат вывода

Доступные байты в файле: 35
Чтенные данные из файла:
Это строка текста в файле.

В примере, приведенном выше, мы использовали класс FileInputStream для создания потока ввода. Поток ввода связан с файломinput.txtссылка.

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

Чтобы изinput.txtДля чтения данных из файла мы реализовали эти два метода.

input.read(array);      //Чтение данных из потока ввода
input.close();             //Закрыть поток ввода