FileInputStream

FileInputStream is a byte stream class used to read raw bytes from a file. It is useful for reading binary files, such as images, audio files, PDFs, etc.It is part of the java.io package and a subclass of InputStream.

Commonly Used Constructors and Methods

Simple Program

Mahesh wants to read the content of a file named "demo.txt" and display it on the console using FileInputStream.

import java.io.FileInputStream;
import java.io.IOException;

public class FileInputStreamExample {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("demo.txt")) {
            int data;
            while ((data = fis.read()) != -1) {
                System.out.print((char) data);
            }
        } catch (IOException e) {
            System.out.println("File error: " + e.getMessage());
        }
    }
}

Output: If demo.txt contains:

Hello LotusJavaPrince!

Then the output will be:

Hello LotusJavaPrince!

FileInputStream is ideal when you need to read binary data or work at the byte level.

  • It’s not recommended for reading text files where encoding matters — use FileReader or BufferedReader for that.
  • It’s best paired with BufferedInputStream for performance in real-world applications.
  • Always close the stream after use or use try-with-resources for automatic closure.
Scroll to Top