00:00

FileInputStream Class in Java: Reading Bytes from a File

Last updated:

When a program needs the exact bytes of a file, such as an image, a firmware update or a binary sensor log, FileInputStream is the most direct tool in java.io. It opens a file and reads its bytes without changing them.

This tutorial covers the class, its constructors and methods, two practical examples and the mistakes to avoid.

1. What Is FileInputStream in Java?

FileInputStream is a concrete subclass of InputStream that reads bytes from a file in the file system. It has been available since Java 1.0.

  • It reads raw bytes; for text, wrap it in an InputStreamReader or use a FileReader.
  • It is not buffered: each read() call goes to the operating system, so wrap it in a BufferedInputStream when reading byte by byte.
  • Opening a missing file, or a folder, throws FileNotFoundException.

2. FileInputStream Class Hierarchy

FileInputStream class hierarchyFileInputStream extends the abstract class InputStream, which extends Object. It implements Closeable and AutoCloseable. It can read from a file path given as a String, a File object or a FileDescriptor.ObjectextendsInputStreamabstract classextendsFileInputStreamreads raw bytes from a fileCloseableAutoCloseableimplementsReads froma file path (String)a File objecta FileDescriptor

Swipe sideways to see the whole diagram.

3. Constructors of FileInputStream

ConstructorDescription
FileInputStream(String name)Opens the file at the given path.
FileInputStream(File file)Opens the file represented by a File object.
FileInputStream(FileDescriptor fdObj)Uses an existing connection to an open file.

The first two throw FileNotFoundException if the file does not exist, is a directory or cannot be opened for reading.

4. Commonly Used Methods

MethodDescription
int read()Reads one byte (0–255), or returns -1 at the end of the file.
int read(byte[] b, int off, int len)Reads up to len bytes into the array and returns how many were read.
int readNBytes(byte[] b, int off, int len)Inherited (Java 9): keeps reading until len bytes are read or the file ends.
long skip(long n)Skips up to n bytes.
int available()Estimated number of bytes that can be read without blocking.
FileChannel getChannel()Returns the NIO channel for this file (Java 1.4).
void close()Closes the file.

5. Example: Reading Sensor Data Byte by Byte

A greenhouse sensor stores one temperature reading per byte. The program reads the log and reports the number of readings, the maximum and the average. It also shows what happens when the file is missing.

SensorLogReader.java
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class SensorLogReader {
    public static void main(String[] args) throws IOException {
        // Each byte is one temperature reading in degrees Celsius
        Path log = Files.createTempFile("sensor", ".bin");
        Files.write(log, new byte[] {21, 22, 22, 24, 27, 31, 29, 25});

        int count = 0, max = Integer.MIN_VALUE, sum = 0;
        try (FileInputStream in = new FileInputStream(log.toFile())) {
            int reading;
            while ((reading = in.read()) != -1) {   // one byte at a time, 0-255
                count++;
                sum += reading;
                max = Math.max(max, reading);
            }
        }
        System.out.println("Readings: " + count + ", max: " + max + " C, average: " + (sum / count) + " C");
        Files.delete(log);

        try (FileInputStream in = new FileInputStream("no-such-sensor.bin")) {
            System.out.println(in.read());
        } catch (FileNotFoundException e) {
            System.out.println("Missing file reported as " + e.getClass().getSimpleName());
        }
    }
}
Output
Readings: 8, max: 31 C, average: 25 C
Missing file reported as FileNotFoundException

How the code works

  1. Files.write() creates a small test log with eight one-byte readings.
  2. read() returns each byte as an int from 0 to 255, so the readings are never negative, and -1 ends the loop.
  3. Opening no-such-sensor.bin throws FileNotFoundException, which the catch block reports.

Reading one byte at a time is fine for eight bytes. For larger files, read into an array or add a BufferedInputStream.

6. Example: Reading a File in Fixed-Size Chunks

A video app uploads large files in 4 KB parts. readNBytes() fills each part completely, except the last one.

ChunkedUpload.java
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class ChunkedUpload {
    public static void main(String[] args) throws IOException {
        Path video = Files.createTempFile("clip", ".mp4");
        Files.write(video, new byte[10_000]);              // a 10,000-byte file

        byte[] chunk = new byte[4096];                     // upload in 4 KB parts
        int part = 0;
        try (FileInputStream in = new FileInputStream(video.toFile())) {
            int n;
            while ((n = in.readNBytes(chunk, 0, chunk.length)) > 0) {
                part++;
                System.out.println("Uploading part " + part + ": " + n + " bytes");
            }
        }
        System.out.println("Parts sent: " + part);
        Files.delete(video);
    }
}
Output
Uploading part 1: 4096 bytes
Uploading part 2: 4096 bytes
Uploading part 3: 1808 bytes
Parts sent: 3

How the code works

  1. readNBytes(chunk, 0, chunk.length) keeps reading until the chunk is full or the file ends, unlike read(), which may return fewer bytes.
  2. It returns 0 at the end of the file, which ends the loop.
  3. 10,000 bytes split into two full 4,096-byte parts and a final 1,808-byte part.

7. Common Mistakes and Best Practices

  • Reading text with FileInputStream. Converting bytes to char one by one breaks non-ASCII text; use a reader with a charset.
  • Reading byte by byte without a buffer. Thousands of system calls make it slow.
  • Ignoring the count returned by read(byte[]). The array may be only partly filled.
  • Leaving the file open. Use try-with-resources; open files can block deletes, especially on Windows.
  • Using available() as the file size. Use Files.size() or File.length() instead.

8. Java Version Improvements and Java 25 Updates

Java versionChange
Java 1.0FileInputStream with its constructors and read() methods.
Java 1.4getChannel() connects it to NIO.
Java 7Try-with-resources; Files.newInputStream() as a modern alternative.
Java 9 to 12Inherits readAllBytes(), readNBytes(), transferTo() and skipNBytes() from InputStream.
Java 25No changes; the class is fully supported.

9. Summary

  • FileInputStream reads raw bytes from a file and extends InputStream.
  • A missing file or a folder causes FileNotFoundException.
  • It is unbuffered, so read into arrays or wrap it in a BufferedInputStream.
  • readNBytes() reads complete chunks; read() may return fewer bytes.
  • Use readers, not FileInputStream, for text.

Related Tutorials

10. Official Java Documentation References