FileInputStream Class in Java: Reading Bytes from a File
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
InputStreamReaderor use aFileReader. - It is not buffered: each
read()call goes to the operating system, so wrap it in aBufferedInputStreamwhen reading byte by byte. - Opening a missing file, or a folder, throws
FileNotFoundException.
2. FileInputStream Class Hierarchy
Swipe sideways to see the whole diagram.
3. Constructors of FileInputStream
| Constructor | Description |
|---|---|
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
| Method | Description |
|---|---|
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.
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());
}
}
}
Readings: 8, max: 31 C, average: 25 C Missing file reported as FileNotFoundException
How the code works
Files.write()creates a small test log with eight one-byte readings.read()returns each byte as anintfrom 0 to 255, so the readings are never negative, and-1ends the loop.- Opening
no-such-sensor.binthrowsFileNotFoundException, which thecatchblock 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.
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);
}
}
Uploading part 1: 4096 bytes Uploading part 2: 4096 bytes Uploading part 3: 1808 bytes Parts sent: 3
How the code works
readNBytes(chunk, 0, chunk.length)keeps reading until the chunk is full or the file ends, unlikeread(), which may return fewer bytes.- It returns
0at the end of the file, which ends the loop. - 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 tocharone 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. UseFiles.size()orFile.length()instead.
8. Java Version Improvements and Java 25 Updates
| Java version | Change |
|---|---|
| Java 1.0 | FileInputStream with its constructors and read() methods. |
| Java 1.4 | getChannel() connects it to NIO. |
| Java 7 | Try-with-resources; Files.newInputStream() as a modern alternative. |
| Java 9 to 12 | Inherits readAllBytes(), readNBytes(), transferTo() and skipNBytes() from InputStream. |
| Java 25 | No changes; the class is fully supported. |
9. Summary
FileInputStreamreads raw bytes from a file and extendsInputStream.- 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
- InputStream Class in Java
- FileOutputStream Class in Java
- BufferedInputStream Class in Java
- FileReader Class in Java