Java FileInputStream Methods
In Java, FileInputStream is used to read data from a file in the form of bytes. It is mainly used for reading binary files such as images, audio files, and other non-text files.
The FileInputStream class belongs to the java.io package.
1. Importing FileInputStream
import java.io.FileInputStream;
import java.io.IOException;
2. Creating a FileInputStream Object
To read a file, we first create an object of FileInputStream.
FileInputStream fis = new FileInputStream("example.txt");
3. read()
The read() method reads a single byte from the file. It returns -1 when the end of file is reached.
FileInputStream fis = new FileInputStream("example.txt");
int data;
while((data = fis.read()) != -1) {
System.out.print((char) data);
}
fis.close();
4. read(byte[] array)
This method reads multiple bytes into an array.
byte[] array = new byte[100];
fis.read(array);
System.out.println(new String(array));
5. available()
The available() method returns the number of remaining bytes that can be read.
System.out.println(fis.available());
6. skip()
The skip() method skips a specified number of bytes.
fis.skip(5); // skips first 5 bytes
7. close()
The close() method closes the stream and releases system resources.
fis.close();
Complete Example with Exception Handling
import java.io.FileInputStream;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("example.txt");
int data;
while((data = fis.read()) != -1) {
System.out.print((char) data);
}
fis.close();
} catch (IOException e) {
System.out.println("An error occurred.");
}
}
}
Important Points
- FileInputStream reads data in byte format.
- It is mainly used for binary files.
- Always close the stream after use.
- Handle exceptions using try-catch block.
- read() returns -1 at the end of the file.
Difference Between FileReader and FileInputStream
- FileInputStream reads bytes.
- FileReader reads characters.
- FileInputStream is used for binary data.
- FileReader is used for text files.
Conclusion
The FileInputStream class provides methods like read(), available(), skip(), and close() to read data from files.
It is useful when working with binary data such as images, audio, or documents.
Tip: Always close the stream to avoid memory leaks and resource issues.