Java FileInputStream

Su Suriya Ravichandran Updated 18 Nov 2026
10 min read ·Lesson 143 of 306

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 dataBytes (0–255)Characters (char)
DecodingNone — bytes are returned exactly as storedBytes are decoded into characters with a charset
Use forBinary files: images, PDFs, ZIP archives, audio, encrypted data, checksumsText 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:

  1. new FileInputStream("price.txt") opens the file for reading. The stream must be closed, so it's created in try-with-resources.
  2. read() returns the next byte as an int from 0 to 255, or -1 at the end of the file. It returns int rather than byte precisely so that -1 can mean "no more data": every value from 0 to 255 is a valid byte.
  3. The bytes are the UTF-8 encoding of the text: R, s and the space are one byte each; ₹ is three bytes (E2 82 B9); 9 is one byte. No decoding happens — that's what makes this a byte stream.
  4. Java's byte type is signed (-128 to 127). Casting the values above 127 to byte gives negative numbers: 226 becomes -30. The bits are the same; only the interpretation differs. To turn a byte back into its unsigned value, use b & 0xFF or Byte.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 to buffer.length bytes and returns how many it actually read, or -1 at the end.
  • The last chunk contains only 1,808 bytes. The remaining positions of buffer still hold bytes from the previous chunk, so only the first n bytes are valid. Code must always use n — for example out.write(buffer, 0, n) or digest.update(buffer, 0, n) — never the whole array.
  • read is 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 value 4096 % 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)
MethodBehaviour
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:

  1. Signatures as byte arrays. Values above 127, such as 0x89 and 0xFF, need a (byte) cast because they don't fit into Java's signed byte literal range. Character literals like 'P' are converted to their byte values automatically.
  2. 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.
  3. 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.
  4. The fake avatar.jpg is actually PHP code. Its extension says JPEG, but its content doesn't start with FF D8 FF, so it's reported as unknown and an upload handler would reject it.
  5. .docx files are ZIP archives (as are .xlsx, .pptx, .jar and .apk), so they share the PK\3\4 signature; 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:

  1. MessageDigest.getInstance("SHA-256") creates a SHA-256 hasher. Every Java implementation must support SHA-256, so the checked NoSuchAlgorithmException can'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.
  2. The loop feeds the file in 8 KB chunks with digest.update(buffer, 0, n). Passing n is essential: the final chunk is usually shorter than the buffer, and hashing the stale bytes after position n would give a wrong checksum.
  3. digest.digest() finishes the calculation and returns the 32-byte result, and HexFormat (Java 17+) converts it to the familiar 64-character hexadecimal form.
  4. The second line hashes the 5-byte text hello. Its SHA-256 is a well-known value, which you can confirm with sha256sum on Linux, shasum -a 256 on macOS or certutil -hashfile hello.txt SHA256 on 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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java FileInputStream and get answers drawn from it.

Signed-in readers only.