Java FileInputStream Class


In Java, file handling is a crucial part of I/O (Input/Output) operations. The FileInputStream class, part of the java.io package, allows developers to read data from files in the form of bytes. Unlike reading text data with FileReader, FileInputStream is specifically designed for reading binary data such as images, audio files, or any non-text files.


What is the FileInputStream Class?

The FileInputStream class is a subclass of InputStream** and is designed for reading byte data from files. It provides the capability to open a file and read its contents byte by byte or in chunks. **FileInputStream` is commonly used for reading files like images, audio, and any other binary file types.

Some key features of FileInputStream include:

  • It reads bytes from a file, which is perfect for handling non-text (binary) data.
  • It provides a way to handle large files in a memory-efficient manner.
  • It supports reading files in an InputStream manner (i.e., byte by byte).

Key Methods of the FileInputStream Class

The FileInputStream class inherits methods from InputStream, but it also provides specific methods for working with files. Here are some important methods:

  1. int read():
    Reads the next byte of data from the file. Returns the byte read as an integer value, or -1 if the end of the file is reached.

  2. int read(byte[] b):
    Reads up to b.length bytes of data into a byte array. Returns the number of bytes actually read, or -1 if the end of the file is reached.

  3. int read(byte[] b, int off, int len):
    Reads a specified number of bytes (up to len) from the file into the byte array b starting from the specified offset off.

  4. long skip(long n):
    Skips over n bytes of data in the file. Returns the actual number of bytes skipped.

  5. int available():
    Returns an estimate of the number of bytes that can be read without blocking. This can be used to check the remaining data in the file.

  6. void close():
    Closes the file input stream and releases any system resources associated with it.

  7. boolean markSupported():
    Returns true if the stream supports the mark() and reset() methods (not all streams support this).


Using the Java FileInputStream Class: Practical Examples

Example 1: Reading Data from a File Using FileInputStream

The most basic use of FileInputStream is to read data from a file. Below is an example of how to read the contents of a text file byte by byte.

import java.io.*;

public class FileInputStreamExample {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("example.txt")) {
            int content;
            while ((content = fis.read()) != -1) {
                System.out.print((char) content);  // Print each byte as a character
            }
        } catch (IOException e) {
            System.out.println("An error occurred while reading the file.");
            e.printStackTrace();
        }
    }
}

Explanation:

  • A FileInputStream is created to read the file example.txt.
  • The read() method reads the file byte by byte until the end of the file (indicated by -1).
  • Each byte is printed after being cast to a char.

Output:

This is the content of example.txt file.

Example 2: Reading Data into a Byte Array

Instead of reading data byte by byte, you can read multiple bytes at once into a byte array. This is typically faster for large files.

import java.io.*;

public class FileInputStreamArrayExample {
    public static void main(String[] args) {
        byte[] buffer = new byte[1024];  // Buffer to hold bytes read from the file
        
        try (FileInputStream fis = new FileInputStream("example.txt")) {
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                System.out.print(new String(buffer, 0, bytesRead));  // Print the bytes read
            }
        } catch (IOException e) {
            System.out.println("An error occurred while reading the file.");
            e.printStackTrace();
        }
    }
}

Explanation:

  • A byte[] buffer is used to store the data read from the file.
  • The read(byte[] b) method reads up to 1024 bytes at a time.
  • The number of bytes read is returned and printed as a string.

Output:

This is the content of example.txt file.

Example 3: Skipping Bytes in a File

Sometimes, you might want to skip a certain number of bytes in the file. The skip(long n) method helps with that.

import java.io.*;

public class FileInputStreamSkipExample {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("example.txt")) {
            // Skip the first 10 bytes of the file
            long skippedBytes = fis.skip(10);
            System.out.println("Skipped " + skippedBytes + " bytes.");
            
            int content;
            while ((content = fis.read()) != -1) {
                System.out.print((char) content);
            }
        } catch (IOException e) {
            System.out.println("An error occurred while reading the file.");
            e.printStackTrace();
        }
    }
}

Explanation:

  • The skip() method is used to skip the first 10 bytes of the file.
  • The remaining bytes are read and printed after skipping.

Output:

Skipped 10 bytes.
is the content of example.txt file.

Closing the FileInputStream

When you're done reading from the file, it's important to close the FileInputStream to free up system resources. This can be done manually by calling the close() method or automatically using a try-with-resources block (which is the recommended approach).


Advantages of Using FileInputStream

  1. Efficient for Binary Data: FileInputStream is optimized for reading binary files, such as images, audio, or any other files that contain raw byte data.
  2. Flexible: You can read files byte by byte or in chunks using a buffer, depending on your needs.
  3. Supports Large Files: With FileInputStream, you can read large files efficiently by reading chunks at a time, without loading the entire file into memory.