Introduction
Reading data from files is one of the most common tasks in Java programming. Applications often need to load images, documents, audio files, videos, configuration files, or other types of stored data. While classes such as FileReader and BufferedReader are designed for reading text files, Java also provides classes for reading binary data.
One of the most important classes for this purpose is FileInputStream. The FileInputStream class belongs to the java.io package and is used to read raw bytes from a file. Since it works with bytes instead of characters, it is ideal for reading binary files such as images, PDF documents, ZIP files, executable files, and multimedia content.
FileInputStream can also read text files, but it is generally recommended to use FileReader or BufferedReader for text because they correctly handle character encoding.
What is FileInputStream?
FileInputStream is a Java class used to read data from a file as a stream of bytes.
Package:
import java.io.FileInputStream;
It is mainly used for:
- Images
- PDF files
- Audio files
- Video files
- ZIP archives
- Binary application data
Since every file is ultimately stored as bytes, FileInputStream provides a low-level mechanism for reading file contents.
Why Use FileInputStream?
FileInputStream is useful because it:
- Reads raw byte data
- Supports binary file processing
- Works with any file type
- Integrates with buffered streams
- Can be combined with higher-level classes for improved performance
It is commonly used in applications that handle binary data such as file upload systems, media players, and document processing tools.
How FileInputStream Works?
When a FileInputStream is created, Java opens a connection to the specified file.
Each call to the read() method retrieves one or more bytes from the file until the end of the stream is reached.
When there is no more data available, read() returns -1.
Finally, the stream should be closed to release system resources.
Creating a FileInputStream
The simplest way is to specify the file name.
Syntax
FileInputStream input =
new FileInputStream("sample.txt");
This opens the file for reading.
Reading a File Byte by Byte
The read() method reads one byte at a time.
Example
import java.io.FileInputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
FileInputStream input =
new FileInputStream("sample.txt");
int data;
while((data = input.read()) != -1) {
System.out.print((char) data);
}
input.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
Sample File (sample.txt)
Hello Java
Output
Each byte is cast to a character for display.
Reading Data into a Byte Array
Reading multiple bytes at once is more efficient than reading one byte at a time.
Example
import java.io.FileInputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
FileInputStream input =
new FileInputStream("sample.txt");
byte[] buffer = new byte[1024];
int bytesRead = input.read(buffer);
System.out.println(
new String(buffer, 0, bytesRead)
);
input.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
Output
Using a byte array reduces the number of read operations.
Reading Binary Files
FileInputStream is ideal for binary files.
Example
import java.io.FileInputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
FileInputStream input =
new FileInputStream("image.png");
int data;
while((data = input.read()) != -1) {
// Process binary data
}
input.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
The bytes can then be copied, stored, or processed as required.
Common FileInputStream Methods
read()
Reads one byte.
int value = input.read();
Returns:
- Byte value (0–255)
- -1 when the end of the file is reached
read(byte[])
Reads multiple bytes into an array.
byte[] buffer = new byte[1024];
input.read(buffer);
This method is faster than reading one byte at a time.
available()
Returns the estimated number of bytes that can be read without blocking.
System.out.println(input.available());
This is useful for checking the amount of remaining data but should not be used as the sole way to determine the total file size.
skip()
Skips a specified number of bytes.
input.skip(10);
This moves the reading position forward.
close()
Closes the input stream.
input.close();
Always close the stream after use.
Using try-with-resources (Recommended)
The recommended way to use FileInputStream is with try-with-resources.
import java.io.FileInputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try (FileInputStream input =
new FileInputStream("sample.txt")) {
int data;
while((data = input.read()) != -1) {
System.out.print((char) data);
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
The stream is automatically closed even if an exception occurs.
FileInputStream vs FileReader
| FileInputStream | FileReader |
|---|---|
| Reads bytes | Reads characters |
| Suitable for binary files | Suitable for text files |
| Does not handle character encoding | Handles character decoding |
| Used for images, PDFs, ZIP files | Used for text documents |
| Returns byte values | Returns character values |
FileInputStream vs BufferedInputStream
| FileInputStream | BufferedInputStream |
|---|---|
| Reads directly from the file | Uses an internal buffer |
| Slower for repeated small reads | Faster due to buffering |
| Lower-level API | Better performance for large files |
Real-Life Example
Suppose you are developing a document upload system that reads a PDF file before storing it in a database.
import java.io.FileInputStream;
import java.io.IOException;
public class DocumentReader {
public static void main(String[] args) {
try (FileInputStream input =
new FileInputStream("report.pdf")) {
byte[] buffer = new byte[4096];
while(input.read(buffer) != -1) {
// Process or upload data
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
Applications that manage files, cloud storage, and multimedia commonly use this approach.
Advantages of FileInputStream
- Reads binary files efficiently
- Works with all file types
- Easy to use
- Supports byte arrays
- Can be combined with buffered streams
- Suitable for low-level file processing
Limitations of FileInputStream
- Reads bytes instead of characters
- Not ideal for text files with different character encodings
- Slower than buffered streams when reading one byte at a time
- Requires explicit exception handling
Common Mistakes
1. Using FileInputStream for Text Processing
Incorrect:
FileInputStream input =
new FileInputStream("students.txt");
While this works, use BufferedReader or FileReader for text because they correctly handle character encoding.
2. Forgetting to Close the Stream
Incorrect:
FileInputStream input =
new FileInputStream("sample.txt");
Correct:
input.close();
Or use try-with-resources.
3. Reading One Byte at a Time for Large Files
Reading byte by byte is less efficient for large files.
Prefer:
byte[] buffer = new byte[4096];
input.read(buffer);
4. Ignoring Exceptions
Always handle IOException.
try {
} catch(IOException e) {
e.printStackTrace();
}
Best Practices
- Use FileInputStream for binary files.
- Use BufferedInputStream for better performance with large files.
- Read data into byte arrays instead of single bytes whenever possible.
- Always use try-with-resources.
- Handle exceptions properly.
- Use FileReader or BufferedReader for text files.
- Close streams promptly to release system resources.
Conclusion
The Java FileInputStream class is an essential part of Java’s I/O library for reading binary data from files. It provides a simple and flexible way to access raw bytes, making it ideal for working with images, PDFs, audio files, videos, and other binary content. While it can also read text files, character-based classes such as FileReader and BufferedReader are usually more appropriate for textual data.