Curriculum
In Java, an InputStream is an abstract class that represents an input stream of bytes. It is the superclass of all classes representing an input stream of bytes. The InputStream class provides a standardized interface for reading data from different input sources, such as files, network connections, and byte arrays. Here is an example of how the InputStream class is used in Java:
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; public class InputStreamExample { public static void main(String[] args) { try { InputStream input = new FileInputStream("input.txt"); int data = input.read(); while (data != -1) { System.out.print((char) data); data = input.read(); } input.close(); } catch (IOException e) { System.out.println("An error occurred while reading the file: " + e.getMessage()); } } }
In this example, we create an InputStream from a file named “input.txt”. We use the read()
method to read one byte at a time from the input stream, and we print the bytes as characters until we reach the end of the stream (-1). We then close the input stream using the close()
method.
The InputStream class in Java has the following methods:
int read() throws IOException
: Reads the next byte of data from the input stream and returns it as an integer between 0 and 255. Returns -1 if the end of the stream has been reached.int read(byte[] b) throws IOException
: Reads up to b.length
bytes of data from the input stream into an array of bytes. Returns the total number of bytes read, or -1 if the end of the stream has been reached.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
. Returns the total number of bytes read, or -1 if the end of the stream has been reached.long skip(long n) throws IOException
: Skips over and discards n
bytes of data from the input stream. Returns the actual number of bytes skipped.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. Subsequent calls to reset()
will reposition the stream to this point.void reset() throws IOException
: Resets the input stream to the position marked by the mark()
method.boolean markSupported()
: Returns true if the input stream supports the mark()
and reset()
methods.