Curriculum
In Java, FileInputStream is a class that extends the InputStream class and allows you to read data from a file in the form of bytes. It is used to read data from a file in a byte-by-byte manner, and it is useful for reading binary data, such as images, videos, and audio files. Here is an example of how the FileInputStream class is used in Java:
import java.io.FileInputStream;
import java.io.IOException;
public class FileInputStreamExample {
public static void main(String[] args) {
try {
FileInputStream fileInput = new FileInputStream("example.txt");
int data = fileInput.read();
while (data != -1) {
System.out.print((char) data);
data = fileInput.read();
}
fileInput.close();
} catch (IOException e) {
System.out.println("An error occurred while reading the file: " + e.getMessage());
}
}
}
In this example, we create a FileInputStream from a file named “example.txt”. We use the read() method to read one byte at a time from the file, and we print the bytes as characters until we reach the end of the file (-1). We then close the input stream using the close() method.
The FileInputStream class in Java has the following methods:
int read() throws IOException: Reads the next byte of data from the file input stream and returns it as an integer between 0 and 255. Returns -1 if the end of the file has been reached.int read(byte[] b) throws IOException: Reads up to b.length bytes of data from the file input stream into an array of bytes. Returns the total number of bytes read, or -1 if the end of the file has been reached.int read(byte[] b, int off, int len) throws IOException: Reads up to len bytes of data from the file input stream into an array of bytes, starting at the specified offset off. Returns the total number of bytes read, or -1 if the end of the file has been reached.long skip(long n) throws IOException: Skips over and discards n bytes of data from the file input stream. Returns the actual number of bytes skipped.int available() throws IOException: Returns an estimate of the number of bytes that can be read from the file input stream without blocking.void close() throws IOException: Closes the file input stream and releases any system resources associated with it.Note that the FileInputStream class should always be used in combination with a try-catch block to handle any potential exceptions that may occur during file input.