Java FileInputStream
📂 Java FileInputStream
FileInputStream is a byte stream class used to read raw byte data from a file.
It is mainly used for binary files like images, videos, or any non-text files, but can also read text files.
-
Package:
java.io -
Superclass:
InputStream
✅ Syntax
1. Reading a File Byte by Byte
-
Reads one byte at a time.
-
Returns -1 when end-of-file (EOF) is reached.
2. Reading Multiple Bytes into a Byte Array
-
More efficient than reading byte by byte.
-
Converts bytes to string using
new String(buffer, 0, bytesRead).
3. Reading a Binary File (Example: Image)
-
Reads binary data efficiently using a buffer.
-
Useful for copying files, images, audio, etc.
4. Important Methods
| Method | Description |
|---|---|
read() |
Reads one byte; returns -1 at EOF |
read(byte[] b) |
Reads multiple bytes into array |
available() |
Returns number of bytes that can be read without blocking |
close() |
Closes the stream to release system resources |
✅ Best Practices
-
Always close the stream after usage (use try-with-resources).
-
Use buffers for reading large files to improve performance.
-
Handle
IOExceptionproperly.
Summary
-
FileInputStream= byte stream → suitable for binary files -
Read byte by byte or in chunks using a byte array.
-
Use try-with-resources to automatically close streams.
