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

Tutoriel de base Java

contrôle de flux Java

Java tableau

Java orienté objet (I)

Java orienté objet (II)

Java orienté objet (III)

Gestion des exceptions Java

Java List

Java Queue (file d'attente)

Java Map collection

Java Set collection

Java Entrée/Sortie (I/O)/O)

Java Reader/Writer

Autres sujets Java

Classe Java ByteArrayInputStream

Dans ce tutoriel, nous allons apprendre la classe Java ByteArrayInputStream et ses méthodes à l'aide d'exemples.

La classe ByteArrayInputStream du paquet java.io peut être utilisée pour lire l'array de données d'entrée (en tant que bytes).

Il hérite de la classe abstraite InputStream.

AttentionDans ByteArrayInputStream, utilisez un tableau de bytes pour créer un flux d'entrée. Il inclut un tableau interne, utilisé pour stocker les données du tableau de bytes spécifique.

Création d'un ByteArrayInputStream

Pour créer un InputStream de tableau de bytes, nous devons d'abord importer le paquet java.io.ByteArrayInputStream. Après avoir importé le paquet, nous pouvons créer un flux d'entrée.

//Création d'un ByteArrayInputStream pour lire l'ensemble de l'array
ByteArrayInputStream input = new ByteArrayInputStream(byte[] arr);

Dans ce cas, nous avons créé un flux d'entrée qui lit l'ensemble des données de l'array arr. Cependant, nous pouvons également créer un flux d'entrée qui ne lit qu'une partie de l'array.

//Création d'un ByteArrayInputStream pour lire une partie de l'array
ByteArrayInputStream input = new ByteArrayInputStream(byte[] arr, int start, int length);

Dans ce cas, le flux d'entrée commence à lire une quantité de bytes égale à length à partir de la position start de l'array.

Méthodes de ByteArrayInputStream

La classe ByteArrayInputStream fournit des implémentations pour différentes méthodes de la classe InputStream.

Méthode read()

  • read()  - Lecture d'un byte individuel à partir de l'array existant dans le flux d'entrée

  • read(byte[] array)  - Lecture de bytes à partir du flux d'entrée et stockage dans l'array spécifié

  • read(byte[] array, int start, int length) - Lecture de la quantité de bytes égale à length à partir du flux et stockage à partir de la position start dans l'array spécifié

Example: ByteArrayInputStream reading data

import java.io.ByteArrayInputStream;
public class Main {
  public static void main(String[] args) {
    //Create a byte array
    byte[] array = {1, 2, 3, 4};
    try {
      ByteArrayInputStream input = new ByteArrayInputStream(array);
      System.out.print("Bytes read from the input stream: ");
      for(int i = 0; i < array.length;++) {
        //Read bytes
        int data = input.read();
        System.out.print(data + ");
      }
      input.close();
    }
    catch(Exception e) {
      e.getStackTrace();
    }
  }
}

Output result

Bytes read from the input stream: 1, 2, 3, 4,

In the above example, we created a byte array input stream named input.

ByteArrayInputStream input = new ByteArrayInputStream(array);

Here, the input stream includes all data from the specified array. To read data from the input stream, we used the read() method.

available() method

To get the number of available bytes in the input stream, we can use the available() method. For example,

import java.io.ByteArrayInputStream;
public class Main {
  public static void main(String args[]) {
    //Create a byte array
    byte[] array = { 1, 2, 3, 4 };
    try {
      ByteArrayInputStream input = new ByteArrayInputStream(array);
      //Returns the number of available bytes
      System.out.println("Available byte count at the start: "); + input.available());
      //Read two bytes from the input stream
      input.read();
      input.read();
      //Returns the number of available bytes
      System.out.println("Available byte count at the end: "); + input.available());
      input.close();
    }
    catch (Exception e) {
      e.getStackTrace();
    }
  }
}

Output result

Available byte count at the start: 4
Available byte count at the end: 2

In the above example,

  1. We have used the available() method to check the number of available bytes in the input stream.

  2. Then, we use the read() method2time from the input stream2bytes.

  3. Now, at the reading2bytes after, we checked the available bytes. This time, the available bytes decreased2.

skip() method

To discard and skip specified bytes, you can use the skip() method. For example

import java.io.ByteArrayInputStream;
public class Main {
  public static void main(String args[]) {
    //Create a byte array
    byte[] array = { 1, 2, 3, 4 };
    try {
      ByteArrayInputStream input = new ByteArrayInputStream(array);
      //Using the skip() method
      input.skip(2;
      System.out.print("Skip ");2bytes after the input stream: ");
      int data = input.read();
      while (data != -1) {
        System.out.print(data + ");
        data = input.read();
      }
      // close() method
      input.close();
    }
    catch (Exception e) {
      e.getStackTrace();
    }
  }
}

Output result

Skip2bytes after the input stream: 3, 4,

In the above example, we use the skip() method to skip2byte data. Therefore, it will not read from the input stream1and2.

close() method

To close the input stream, you can use the close() method.

However, the close() method does not work in the ByteArrayInputStream class. Even after the close() method is called, we can still use the methods of this class.

Other methods of ByteArrayInputStream

MethodContent description
finalize()Ensure that the close() method is called
mark()Mark the position of the data read from the input stream
reset()Return the control to the point in the input stream where the mark was set
markSupported()Check if the input stream supports mark() and reset()