Junior — Middle
What is the role and purpose of the InputStream class in Java?
sobes.tech AI
Answer from AI
The InputStream class in Java is an abstract base class for all byte input streams. Its main role is to provide a unified interface for reading data from various sources such as files, network connections, byte arrays, and others.
The purpose of InputStream is to ensure sequential reading of bytes, hiding the details of the specific data source. It defines methods, for example, read(), which allow reading a single byte or an array of bytes.
Example usage:
InputStream input = new FileInputStream("file.txt");
int data = input.read();
while(data != -1) {
System.out.print((char) data);
data = input.read();
}
input.close();
Thus, InputStream serves as the foundation for working with input streams in Java, providing flexibility and extensibility.