Java InputStream

https://‮www‬.theitroad.com

InputStream is an abstract class in Java that provides a standard way of reading data from different sources in the form of bytes. It is the superclass of all classes that represent an input stream of bytes.

The most commonly used subclasses of InputStream include:

  • FileInputStream: used for reading data from a file.
  • ByteArrayInputStream: used for reading data from a byte array.
  • DataInputStream: used for reading primitive data types from an input stream.

Here's an example of using the FileInputStream class to read data from a file:

import java.io.*;

public class FileInputStreamExample {
    public static void main(String[] args) {
        try {
            FileInputStream input = new FileInputStream("file.txt");
            int data = input.read();
            while (data != -1) {
                System.out.print((char) data);
                data = input.read();
            }
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, we create a FileInputStream object and pass the name of the file we want to read from as a parameter. We then read the data from the file one byte at a time using the read method of the FileInputStream object. The read method returns -1 when it reaches the end of the file, so we use this value to terminate the loop.

Finally, we close the FileInputStream object using the close method to release any system resources associated with the stream.

It's important to note that the read method of the InputStream class reads a single byte at a time, so it is not very efficient when reading large amounts of data. To read data more efficiently, you can use the BufferedInputStream class, which reads data into an internal buffer and provides methods for reading data in larger chunks.

Overall, the InputStream class provides a flexible and efficient way of reading data from different sources in Java. By using the various subclasses of InputStream, you can read data from files, network connections, and other input sources in the form of bytes.