Clase Java BufferedInputStream
Clase Java BufferedInputStream
En este tutorial, aprenderemos sobre Java BufferedInputStream y sus métodos con la ayuda de ejemplos.
El BufferedInputStream
clase del java.io
El paquete se usa con otros flujos de entrada para leer los datos (en bytes) de manera más eficiente.
Extiende el InputStream
clase abstracta.
Funcionamiento de BufferedInputStream
El BufferedInputStream
mantiene un buffer interno de 8192 bytes .
Durante la operación de lectura en BufferedInputStream
, se lee una porción de bytes del disco y se almacena en el búfer interno. Y desde el búfer interno los bytes se leen individualmente.
Por lo tanto, se reduce el número de comunicaciones con el disco. Es por eso que leer bytes es más rápido usando BufferedInputStream
.
Crear un BufferedInputStream
Para crear un BufferedInputStream
, debemos importar el java.io.BufferedInputStream
paquete primero. Una vez que importamos el paquete, aquí es cómo podemos crear el flujo de entrada.
// Creates a FileInputStream
FileInputStream file = new FileInputStream(String path);
// Creates a BufferedInputStream
BufferedInputStream buffer = new BufferInputStream(file);
En el ejemplo anterior, hemos creado un BufferdInputStream
llamado búfer con el FileInputStream
llamado archivo .
Aquí, el búfer interno tiene el tamaño predeterminado de 8192 bytes. Sin embargo, también podemos especificar el tamaño del búfer interno.
// Creates a BufferedInputStream with specified size internal buffer
BufferedInputStream buffer = new BufferInputStream(file, int size);
El búfer ayudará a leer bytes de los archivos más rápidamente.
Métodos de BufferedInputStream
El BufferedInputStream
La clase proporciona implementaciones para diferentes métodos presentes en el InputStream
clase.
método read()
read()
- lee un solo byte del flujo de entradaread(byte[] arr)
- lee bytes de la secuencia y los almacena en la matriz especificadaread(byte[] arr, int start, int length)
- lee el número de bytes igual a la longitud de la secuencia y se almacena en la matriz especificada a partir de la posición inicio
Supongamos que tenemos un archivo llamado input.txt con el siguiente contenido.
This is a line of text inside the file.
Intentemos leer el archivo usando BufferedInputStream
.
import java.io.BufferedInputStream;
import java.io.FileInputStream;
class Main {
public static void main(String[] args) {
try {
// Creates a FileInputStream
FileInputStream file = new FileInputStream("input.txt");
// Creates a BufferedInputStream
BufferedInputStream input = new BufferedInputStream(file);
// Reads first byte from file
int i = input .read();
while (i != -1) {
System.out.print((char) i);
// Reads next byte from the file
i = input.read();
}
input.close();
}
catch (Exception e) {
e.getStackTrace();
}
}
}
Salida
This is a line of text inside the file.
En el ejemplo anterior, hemos creado un flujo de entrada almacenado en búfer llamado buffer junto con FileInputStream
. El flujo de entrada está vinculado con el archivo input.txt .
FileInputStream file = new FileInputStream("input.txt");
BufferedInputStream buffer = new BufferedInputStream(file);
Aquí, hemos usado el read()
método para leer una matriz de bytes del búfer interno del lector almacenado en búfer.
método disponible()
Para obtener la cantidad de bytes disponibles en el flujo de entrada, podemos usar available()
método. Por ejemplo,
import java.io.FileInputStream;
import java.io.BufferedInputStream;
public class Main {
public static void main(String args[]) {
try {
// Suppose, the input.txt file contains the following text
// This is a line of text inside the file.
FileInputStream file = new FileInputStream("input.txt");
// Creates a BufferedInputStream
BufferedInputStream buffer = new BufferedInputStream(file);
// Returns the available number of bytes
System.out.println("Available bytes at the beginning: " + buffer.available());
// Reads bytes from the file
buffer.read();
buffer.read();
buffer.read();
// Returns the available number of bytes
System.out.println("Available bytes at the end: " + buffer.available());
buffer.close();
}
catch (Exception e) {
e.getStackTrace();
}
}
}
Salida
Available bytes at the beginning: 39 Available bytes at the end: 36
En el ejemplo anterior,
- Primero usamos el
available()
para comprobar el número de bytes disponibles en el flujo de entrada. - Entonces, hemos usado el
read()
método 3 veces para leer 3 bytes del flujo de entrada. - Ahora, después de leer los bytes, nuevamente hemos verificado los bytes disponibles. Esta vez los bytes disponibles se redujeron en 3.
método skip()
Para descartar y omitir el número especificado de bytes, podemos usar el skip()
método. Por ejemplo,
import java.io.FileInputStream;
import java.io.BufferedInputStream;
public class Main {
public static void main(String args[]) {
try {
// Suppose, the input.txt file contains the following text
// This is a line of text inside the file.
FileInputStream file = new FileInputStream("input.txt");
// Creates a BufferedInputStream
BufferedInputStream buffer = new BufferedInputStream(file);
// Skips the 5 bytes
buffer.skip(5);
System.out.println("Input stream after skipping 5 bytes:");
// Reads the first byte from input stream
int i = buffer.read();
while (i != -1) {
System.out.print((char) i);
// Reads next byte from the input stream
i = buffer.read();
}
// Closes the input stream
buffer.close();
}
catch (Exception e) {
e.getStackTrace();
}
}
}
Salida
Input stream after skipping 5 bytes: is a line of text inside the file.
En el ejemplo anterior, hemos utilizado el skip()
método para omitir 5 bytes del flujo de entrada del archivo. Por lo tanto, los bytes 'T'
, 'h'
, 'i'
, 's'
y ' '
se omiten del flujo de entrada.
Método cerrar()
Para cerrar el flujo de entrada almacenado en búfer, podemos usar close()
método. Una vez que el close()
se llama al método, no podemos usar el flujo de entrada para leer los datos.
Otros métodos de BufferedInputStream
Métodos | Descripciones |
---|---|
mark() | marcar la posición en el flujo de entrada hasta el cual se han leído los datos |
reset() | devuelve el control al punto en el flujo de entrada donde se estableció la marca |
Para obtener más información, visite Java BufferdInputStream (documentación oficial de Java).
Java