Java FileInputStream
What FileInputStream Is
java.io.FileInputStream reads the raw bytes of a file. It is a subclass of InputStream, the base class for every byte source in Java (covered in the InputStream lesson).
The key difference from the reader classes in the previous lessons:
FileInputStream (byte stream) | FileReader / BufferedReader (character stream) | |
|---|---|---|
| Unit of data | Bytes (0–255) | Characters (char) |
| Decoding | None — bytes are returned exactly as stored | Bytes are decoded into characters with a charset |
| Use for | Binary files: images, PDFs, ZIP archives, audio, encrypted data, checksums | Text files |
Use a byte stream whenever the content isn't text, or when you need the exact bytes of a file regardless of what they mean — for copying, hashing, uploading or detecting a file type. Reading a binary file through a reader would decode its bytes as characters and corrupt the data.
Reading One Byte at a Time
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
public class I1 {
public static void main(String[] args) throws IOException {
Files.writeString(Path.of("price.txt"), "Rs ₹9", StandardCharsets.UTF_8);
try (FileInputStream in = new FileInputStream("price.txt")) {
int b;
while ((b = in.read()) != -1) {
System.out.printf("%3d 0x%02X as byte: %4d%n", b, b, (byte) b);
}
}
}
}
Output:
82 0x52 as byte: 82
115 0x73 as byte: 115
32 0x20 as byte: 32
226 0xE2 as byte: -30
130 0x82 as byte: -126
185 0xB9 as byte: -71
57 0x39 as byte: 57
What this shows:
new FileInputStream("price.txt")opens the file for reading. The stream must be closed, so it's created in try-with-resources.read()returns the next byte as anintfrom0to255, or-1at the end of the file. It returnsintrather thanbyteprecisely so that-1can mean "no more data": every value from 0 to 255 is a valid byte.- The bytes are the UTF-8 encoding of the text:
R,sand the space are one byte each;₹is three bytes (E2 82 B9);9is one byte. No decoding happens — that's what makes this a byte stream. - Java's
bytetype is signed (-128to127). Casting the values above 127 tobytegives negative numbers:226becomes-30. The bits are the same; only the interpretation differs. To turn abyteback into its unsigned value, useb & 0xFForByte.toUnsignedInt(b). Forgetting this is a classic source of bugs in binary-format code.
Reading one byte per call is fine for this demonstration, but each read() on a FileInputStream is a separate call into the operating system, which makes it very slow for real files. Use a byte array or a BufferedInputStream, shown next.
Reading into a Byte Array
import java.io.*;
import java.nio.file.*;
public class I2 {
public static void main(String[] args) throws IOException {
byte[] data = new byte[10_000];
for (int i = 0; i < data.length; i++) data[i] = (byte) (i % 100);
Files.write(Path.of("data.bin"), data);
try (FileInputStream in = new FileInputStream("data.bin")) {
byte[] buffer = new byte[4096];
int n, chunks = 0;
long total = 0;
while ((n = in.read(buffer)) != -1) {
chunks++;
total += n;
System.out.println("chunk " + chunks + ": " + n + " bytes, first byte " + buffer[0]);
}
System.out.println("total " + total + " bytes");
}
}
}
Output:
chunk 1: 4096 bytes, first byte 0
chunk 2: 4096 bytes, first byte 96
chunk 3: 1808 bytes, first byte 92
total 10000 bytes
This is the standard loop for processing a file of any size with fixed memory:
read(byte[] buffer)fills the array with up tobuffer.lengthbytes and returns how many it actually read, or-1at the end.- The last chunk contains only 1,808 bytes. The remaining positions of
bufferstill hold bytes from the previous chunk, so only the firstnbytes are valid. Code must always usen— for exampleout.write(buffer, 0, n)ordigest.update(buffer, 0, n)— never the whole array. readis also allowed to return fewer bytes than requested in the middle of a stream (this happens with network streams), which is another reason never to assume the buffer is full.- The file was filled with
i % 100, so the first byte of each chunk shows the chunk's position: byte 4,096 has the value4096 % 100 = 96.
A buffer of 4 KB to 64 KB is typical. A buffer much larger than that rarely makes reading faster.
Other Reading Methods
import java.io.*;
import java.nio.file.*;
import java.util.Arrays;
public class I3 {
public static void main(String[] args) throws IOException {
Files.write(Path.of("header.bin"), new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
try (FileInputStream in = new FileInputStream("header.bin")) {
System.out.println("available: " + in.available());
System.out.println("readNBytes(3): " + Arrays.toString(in.readNBytes(3)));
System.out.println("skip(2): " + in.skip(2));
System.out.println("readAllBytes: " + Arrays.toString(in.readAllBytes()));
System.out.println("read at end: " + in.read());
}
try (FileInputStream in = new FileInputStream("header.bin");
OutputStream copy = new FileOutputStream("header-copy.bin")) {
System.out.println("transferTo copied " + in.transferTo(copy) + " bytes");
}
for (String name : new String[] {"missing.bin", "."}) {
try (FileInputStream in = new FileInputStream(name)) {
System.out.println(in.read());
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException: " + e.getMessage());
}
}
}
}
Output (on Linux):
available: 10
readNBytes(3): [1, 2, 3]
skip(2): 2
readAllBytes: [6, 7, 8, 9, 10]
read at end: -1
transferTo copied 10 bytes
FileNotFoundException: missing.bin (No such file or directory)
FileNotFoundException: . (Is a directory)
| Method | Behaviour |
|---|---|
available() | An estimate of how many bytes can be read without blocking. For a local file it's usually the remaining size, but don't use it to size arrays for a whole stream — for network streams it can be 0 even though more data will arrive |
readNBytes(int n) (Java 11+) | Reads up to n bytes, looping internally until it has n bytes or reaches the end. Unlike read(buf), it doesn't return early with a partial result in the middle of the stream |
skip(long n) | Skips bytes and returns how many were actually skipped |
readAllBytes() (Java 9+) | Reads everything remaining into a new array. Convenient for small files; for large files it needs as much memory as the file size |
transferTo(OutputStream) (Java 9+) | Copies all remaining bytes to an output stream and returns the count — the simplest way to copy a stream |
The constructor throws FileNotFoundException (a subclass of IOException) when the file can't be opened for reading — because it doesn't exist, because the path is a directory, or because of missing permissions. The message includes the operating system's reason in parentheses.
Adding a Buffer: BufferedInputStream
When code needs to read small pieces — single bytes, a few bytes of a header, then a field, then another — wrap the stream in a BufferedInputStream. It reads 8 KB at a time from the file and serves the small reads from memory:
try (InputStream in = new BufferedInputStream(new FileInputStream("archive.dat"))) {
int b;
while ((b = in.read()) != -1) {
// byte-by-byte processing is now cheap
}
}
When you already read in large chunks with read(byte[]), an extra BufferedInputStream adds little. Buffered streams are covered in more detail in the Buffered Streams lesson.
FileInputStream and Files.newInputStream
NIO offers an equivalent factory method:
try (InputStream in = Files.newInputStream(Path.of("report.pdf"))) { ... }
Both return an InputStream with the same methods. Files.newInputStream takes a Path, throws the more specific NIO exceptions (NoSuchFileException, AccessDeniedException), and supports open options. FileInputStream is still widely used, and it's required by some older APIs; it also offers getChannel() for access to a FileChannel. For whole small files, Files.readAllBytes(path) avoids streams entirely.
Practical Example: Detecting a File's Real Type
A file's extension is just part of its name, and anyone can rename shell.php to avatar.jpg. Upload handlers therefore check the file's content. Most binary formats start with a fixed sequence of bytes, called a magic number or file signature, so reading the first few bytes is enough to identify them.
import java.io.*;
import java.nio.file.*;
import java.util.*;
public class Sniff {
record Signature(String type, byte[] magic) { }
static final List<Signature> SIGNATURES = List.of(
new Signature("PNG image", new byte[] {(byte) 0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A}),
new Signature("JPEG image", new byte[] {(byte) 0xFF, (byte) 0xD8, (byte) 0xFF}),
new Signature("PDF document", new byte[] {'%', 'P', 'D', 'F', '-'}),
new Signature("ZIP archive (also .docx/.xlsx/.jar)", new byte[] {'P', 'K', 3, 4}));
static String detect(Path file) throws IOException {
byte[] head;
try (InputStream in = new FileInputStream(file.toFile())) {
head = in.readNBytes(8);
}
for (Signature s : SIGNATURES) {
if (head.length >= s.magic().length
&& Arrays.equals(head, 0, s.magic().length, s.magic(), 0, s.magic().length)) {
return s.type();
}
}
return "unknown";
}
public static void main(String[] args) throws IOException {
Files.write(Path.of("photo.png"), new byte[] {(byte) 0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 13});
Files.write(Path.of("invoice.pdf"), "%PDF-1.7\n%...".getBytes());
Files.write(Path.of("resume.docx"), new byte[] {'P', 'K', 3, 4, 20, 0});
Files.write(Path.of("avatar.jpg"), "<?php system($_GET['c']); ?>".getBytes());
Files.write(Path.of("empty.png"), new byte[0]);
for (String name : List.of("photo.png", "invoice.pdf", "resume.docx", "avatar.jpg", "empty.png")) {
System.out.printf("%-12s -> %s%n", name, detect(Path.of(name)));
}
}
}
Output:
photo.png -> PNG image
invoice.pdf -> PDF document
resume.docx -> ZIP archive (also .docx/.xlsx/.jar)
avatar.jpg -> unknown
empty.png -> unknown
How it works:
- Signatures as byte arrays. Values above 127, such as
0x89and0xFF, need a(byte)cast because they don't fit into Java's signedbyteliteral range. Character literals like'P'are converted to their byte values automatically. - Only the first 8 bytes are read with
readNBytes(8), however large the file is. For a file shorter than 8 bytes it returns fewer bytes — zero for the empty file — so the length check prevents an out-of-range comparison. Arrays.equals(a, aFrom, aTo, b, bFrom, bTo)(Java 9+) compares ranges of two arrays, so the beginning of the file can be compared with each signature without copying.- The fake
avatar.jpgis actually PHP code. Its extension says JPEG, but its content doesn't start withFF D8 FF, so it's reported asunknownand an upload handler would reject it. .docxfiles are ZIP archives (as are.xlsx,.pptx,.jarand.apk), so they share thePK\3\4signature; distinguishing them requires looking inside the archive.
Signature checks are one layer of upload validation. Production systems also limit the file size, store uploads under generated names outside the web root, and often re-encode images, because a file can start with a valid signature and still contain malicious content later.
Practical Example: Computing a File Checksum
Software downloads and backups are verified with a checksum: a short fingerprint computed from every byte of the file. If even one byte changes, the checksum changes completely. Streaming the file through a MessageDigest computes it with constant memory, so it works for multi-gigabyte files.
import java.io.*;
import java.nio.file.*;
import java.security.*;
import java.util.HexFormat;
public class Checksum {
static String sha256(Path file) throws IOException {
MessageDigest digest;
try {
digest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("SHA-256 is required on every Java platform", e);
}
try (InputStream in = new BufferedInputStream(new FileInputStream(file.toFile()))) {
byte[] buffer = new byte[8192];
int n;
while ((n = in.read(buffer)) != -1) {
digest.update(buffer, 0, n);
}
}
return HexFormat.of().formatHex(digest.digest());
}
public static void main(String[] args) throws IOException {
Path release = Files.writeString(Path.of("app-1.0.jar"), "pretend this is a large release archive");
String actual = sha256(release);
System.out.println("sha256: " + actual);
System.out.println("hello: " + sha256(Files.writeString(Path.of("hello.txt"), "hello")));
}
}
Output:
sha256: ecd5df44b28850d5a23db35ed203c7297aecbc8cf07989b39b387d99ed49ccae
hello: 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
Step by step:
MessageDigest.getInstance("SHA-256")creates a SHA-256 hasher. Every Java implementation must support SHA-256, so the checkedNoSuchAlgorithmExceptioncan't really happen here; it's converted into an unchecked exception with the original as its cause (Exception Chaining lesson) instead of being declared by every caller.- The loop feeds the file in 8 KB chunks with
digest.update(buffer, 0, n). Passingnis essential: the final chunk is usually shorter than the buffer, and hashing the stale bytes after positionnwould give a wrong checksum. digest.digest()finishes the calculation and returns the 32-byte result, andHexFormat(Java 17+) converts it to the familiar 64-character hexadecimal form.- The second line hashes the 5-byte text
hello. Its SHA-256 is a well-known value, which you can confirm withsha256sumon Linux,shasum -a 256on macOS orcertutil -hashfile hello.txt SHA256on Windows (when the file contains exactly those five bytes, with no newline).
To verify a download, compare the computed value with the one published by the vendor; if they differ, the file is corrupted or has been tampered with. For comparing secrets such as tokens (not public checksums), use MessageDigest.isEqual, which compares in constant time.