English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
En este tutorial, aprenderemos con ejemplos sobre Java ByteArrayInputStream y sus métodos.
La clase ByteArrayInputStream del paquete java.io se puede usar para leer el array de datos de entrada (en bytes).
Hereda de la clase abstracta InputStream.
Nota: En ByteArrayInputStream, se crea un flujo de entrada usando un array de bytes. Incluye un array interno que se utiliza para almacenar los datos del array específico.
Para crear un flujo de entrada de array de bytes, primero debemos importar el paquete java.io.ByteArrayInputStream. Después de importar el paquete, podemos crear el flujo de entrada.
//Crear un ByteArrayInputStream para leer todo el array ByteArrayInputStream input = new ByteArrayInputStream(byte[] arr);
Aquí, creamos un flujo de entrada que lee los datos enteros del array arr. Pero también podemos crear un flujo de entrada que solo lea algunos datos del array.
//Crear un ByteArrayInputStream para leer una parte del array ByteArrayInputStream input = new ByteArrayInputStream(byte[] arr, int start, int length);
Aquí, el flujo de entrada comienza a leer un número de bytes igual a length desde la posición start del array.
La clase ByteArrayInputStream proporciona implementaciones de diferentes métodos en la clase InputStream.
read() - Leer un byte individual desde el array existente en el flujo de entrada
read(byte[] array) - Leer bytes desde el flujo de entrada y almacenarlos en el array especificado
read(byte[] array, int start, int length) - Leer el número de bytes igual a length desde el flujo y almacenarlos en el array especificado desde la posición start
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; i++) { //Read bytes int data = input.read(); System.out.print(data + ""); } input.close(); } catch(Exception e) { e.getStackTrace(); } } }
输出结果
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.
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 number of bytes at the beginning: "); + input.available()); //Read two bytes from the input stream input.read(); input.read(); //Returns the number of available bytes System.out.println("Available number of bytes at the end: "); + input.available()); input.close(); } catch (Exception e) { e.getStackTrace(); } } }
输出结果
Available number of bytes at the beginning: 4 Available number of bytes at the end: 2
In the above example,
We have used the available() method to check the number of available bytes in the input stream.
Then, we use the read() method2time from the input stream2bytes.
Now, in reading2bytes after, we checked the available bytes. This time, the available bytes decreased2.
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); //Use 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() 方法 input.close(); } catch (Exception e) { e.getStackTrace(); } } }
输出结果
跳过2个字节后的输入流: 3, 4,
在上面的示例中,我们使用skip()方法跳过输入流中的2字节数据。因此,不会从输入流中读取1和2.
要关闭输入流,可以使用close()方法。
但是,close()方法在ByteArrayInputStream类中不起作用。即使在close()方法被调用之后,我们也可以使用该类的方法。
方法 | 内容描述 |
---|---|
finalize() | 确保close()方法被调用 |
mark() | 标记输入流中已读取数据的位置 |
reset() | 将控件返回到输入流中设置了标记的点 |
markSupported() | 检查输入流是否支持mark()和reset() |