The FileInputStream
class in Java is part of the java.io
package and is used to read data from a file. It allows for reading raw bytes from a file and is typically used for handling binary data or when reading files in a byte-oriented manner (such as images or audio files).
Key Features:
- Byte-oriented:
FileInputStream
reads data in the form of bytes rather than characters. - Input Stream: It is a subclass of
InputStream
and provides theread()
method to read bytes from a file. - Reading files: It is used to read data from files, including binary files, in contrast to
FileReader
, which is typically used for reading character files.
Commonly Used Methods:
read()
: Reads a single byte of data from the file.read(byte[] b)
: Reads bytes into an array.close()
: Closes the file and releases any system resources associated with the stream.available()
: Returns the number of bytes that can be read without blocking.
Example Usage:
import java.io.FileInputStream;
import java.io.IOException;
public class FileInputStreamExample {
public static void main(String[] args) {
FileInputStream fis = null;
try {
// Creating a FileInputStream to read the file
fis = new FileInputStream("example.txt");
int data;
// Reading the file byte by byte
while1 != -1) {
System.out.print((char) data); // Printing the byte as a character
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// Always close the stream to release resources
try {
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Key Points:
- File Input: Primarily used for reading files, particularly binary data.
- Efficiency:
FileInputStream
reads data one byte at a time, which can be inefficient for larger files. For improved performance, consider using buffered streams (BufferedInputStream
) or reading chunks of data at once. - Exception Handling: Since file operations can result in errors (e.g., file not found, permissions issue), you should always handle
IOException
exceptions appropriately.
In conclusion, FileInputStream
is a fundamental class for working with file input in Java, especially for reading binary files or when working with raw data at the byte level.
- data = fis.read( [↩]