The InputStream class is an abstract class in java.io used for reading byte-based input. It serves as the superclass for all classes representing an input stream of bytes (e.g., FileInputStream, BufferedInputStream, etc.).
Commonly Used Methods

Simple Program: Reading Bytes from a File
Read content from a file using FileInputStream (a subclass of InputStream) and print the contents to the console.
import java.io.FileInputStream;
import java.io.IOException;
public class SimpleInputStreamExample {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("sample.txt")) {
int byteData;
while ((byteData = fis.read()) != -1) {
System.out.print((char) byteData); // casting byte to char
}
} catch (IOException e) {
e.printStackTrace();
}
}
}Notes:
- Make sure
sample.txtexists in your project folder. - It reads byte-by-byte and prints each character.
Problem Statement:
LotusJavaPrince is debugging a production system. The server generates a log.txt file. They want to count the number of ERROR, WARNING, and INFO messages using InputStream. This should work with minimal memory usage—hence byte-level reading.
import java.io.FileInputStream;
import java.io.IOException;
public class LogAnalyzer {
public static void main(String[] args) {
StringBuilder logBuilder = new StringBuilder();
int errorCount = 0;
int warningCount = 0;
int infoCount = 0;
try (FileInputStream fis = new FileInputStream("log.txt")) {
int byteData;
while ((byteData = fis.read()) != -1) {
char ch = (char) byteData;
logBuilder.append(ch);
// When a line ends, process it
if (ch == '\n') {
String line = logBuilder.toString().toUpperCase();
if (line.contains("ERROR")) errorCount++;
if (line.contains("WARNING")) warningCount++;
if (line.contains("INFO")) infoCount++;
logBuilder.setLength(0); // clear for next line
}
}
// Handle last line if not ending in '\n'
if (logBuilder.length() > 0) {
String line = logBuilder.toString().toUpperCase();
if (line.contains("ERROR")) errorCount++;
if (line.contains("WARNING")) warningCount++;
if (line.contains("INFO")) infoCount++;
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Log Analysis Summary:");
System.out.println("ERROR: " + errorCount);
System.out.println("WARNING: " + warningCount);
System.out.println("INFO: " + infoCount);
}
}
Sample log.txt Content
INFO - Server started successfully.
WARNING - Disk space low.
ERROR - Unable to connect to database.
INFO - Retry succeeded.
WARNING - High memory usage.
Output
Log Analysis Summary:
ERROR: 1
WARNING: 2
INFO: 2
InputStream provides low-level byte input.
- Subclasses like
FileInputStreamextend its use for file handling. - You can read byte-by-byte, or into byte arrays.
- It’s useful for efficient I/O, especially with large files.
