FileInputStream is a class that obtains input bytes from a file in a file system. It is a subclass of the abstract InputStream class and is designed for reading streams of raw bytes such as image data. For reading streams of characters, professional developers consider using FileReader instead.
When you create a FileInputStream, Java opens a connection to the file on your hard drive. You can then read data byte-by-byte or in a larger byte array. Because it works with bytes (8-bits), it doesn't care about "text encoding"—it just sees 0s and 1s.
File object.read() to pull data into the JVM.The FileInputStream class provides several methods to navigate and consume file data:
| Method | Description |
|---|---|
int read() |
Reads the next byte of data. Returns -1 if the end of the file is reached. |
int read(byte[] b) |
Reads up to b.length bytes into an array. Much faster than reading byte-by-byte. |
int available() |
Returns an estimate of the number of bytes that can be read without blocking. |
long skip(long n) |
Skips over and discards n bytes of data from the input stream. |
void close() |
Closes the stream and releases system resources. |
Reading one byte at a time is like moving water with a teaspoon—it's very slow. Reading into a byte array is like using a bucket. For performance, always use an array (buffer) when dealing with large files.
Good for very small files or learning the logic.
int data = input.read();
Standard for production. 1KB to 8KB is common.
byte[] buffer = new byte[1024];
This professional example reads a file and converts its bytes into a String. This is the foundation of how "Hex Editors" or "File Analyzers" are built.
A common mistake is using FileInputStream to read a text file (like a .txt or .java file). While it "works," it doesn't handle character encoding (like UTF-8 or UTF-16) correctly. If your file contains Chinese characters or emojis, FileInputStream might break them because it sees them as multiple separate bytes rather than one single character.
When working with FileInputStream, you must handle two primary exceptions:
Q: What does the read() method return?
A: It returns an int. The value is the byte of data (0 to 255) or -1 if the end of the file is reached.
Q: Why is it important to close the FileInputStream?
A: Every open stream consumes a "file handle" in the Operating System. If you open too many streams without closing them, your OS will eventually refuse to open any more files, causing your app to crash.
Q: Can we read from the middle of a file?
A: Yes, you can use the skip(long n) method to move the "cursor" forward by n bytes before you start reading.
FileInputStream is the bedrock of Java I/O. It provides the most direct, unfiltered access to file data. While higher-level APIs exist, understanding how to work with raw bytes is essential for any developer who wants to build high-performance systems or handle non-textual data formats.