Curriculum
In Java, BufferedInputStream
is a class that extends the FilterInputStream
class and provides buffering functionality to input streams. This buffering reduces the number of times the underlying input stream must be accessed and can result in improved performance. Here is an example of how the BufferedInputStream
class is used in Java:
import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; public class BufferedInputStreamExample { public static void main(String[] args) { try { FileInputStream fileInput = new FileInputStream("example.txt"); BufferedInputStream bufferedInput = new BufferedInputStream(fileInput); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = bufferedInput.read(buffer)) != -1) { // process the data read from the input stream } bufferedInput.close(); } catch (IOException e) { System.out.println("An error occurred while reading the file: " + e.getMessage()); } } }
In this example, we create a FileInputStream
to a file named “example.txt”, and we use it to create a BufferedInputStream
. We create a byte array buffer
to store the data read from the input stream, and we use the read()
method of the BufferedInputStream
class to read data from the input stream into the buffer. We then process the data read from the input stream as needed. We close the BufferedInputStream
using the close()
method.
The BufferedInputStream
class in Java has the following methods:
int available() throws IOException
: Returns an estimate of the number of bytes that can be read from the input stream without blocking.void close() throws IOException
: Closes the input stream and releases any system resources associated with it.void mark(int readLimit)
: Marks the current position in the input stream.boolean markSupported()
: Returns true
if the input stream supports the mark()
and reset()
methods.int read() throws IOException
: Reads a single byte of data from the input stream.int read(byte[] b, int off, int len) throws IOException
: Reads up to len
bytes of data from the input stream into an array of bytes, starting at the specified offset off
.void reset() throws IOException
: Resets the input stream to the position marked by the mark()
method.long skip(long n) throws IOException
: Skips over and discards n
bytes of data from the input stream.Note that when using a BufferedInputStream
, it is important to properly close the input stream using the close()
method to ensure that all system resources are released. Additionally, the BufferedInputStream
should be used when reading large amounts of data from an input stream to improve performance by reducing the number of reads from the underlying input stream.