Java FileInputStream Class
In Java, the FileInputStream class is a subclass of the InputStream class that is used to read data from a file in byte-oriented format. It allows you to open a file and read its contents as a stream of bytes.
In this article, we will explore what the Java FileInputStream class is, how it works, and how you can use it to improve your performance in Java.
What is the FileInputStream Class?
The FileInputStream class is a subclass of the InputStream class, providing a way to read data from a file in a byte-by-byte manner. This class can read data from any file on disk, including binary files like images and audio files. FileInputStream is a low-level class that provides a way to read data from files on disk.
How to Create a FileInputStream Object
To use the FileInputStream class, you first need to create an instance of the class. Here’s an example of how to do that:
FileInputStream fis = new FileInputStream("example.txt");
In this example, we create a new FileInputStream object and pass in the name of the file we want to read. The file must be in the same directory as the Java program, or you can provide the full path to the file.
Reading Data with FileInputStream
Once you have a FileInputStream object, you can use it to read data from the file. Here’s an example of how to read a single byte from the file:
int data = fis.read();
This code reads a single byte of data from the file and stores it in the variable “data.” You can use the read() method to read one byte at a time until you’ve read the entire file.
Closing a FileInputStream Object
When you’re done reading from the file, it’s essential to close the FileInputStream object. Here’s how you can do that:
fis.close();
If you don’t close the FileInputStream object, you can run into memory leaks or file locking issues. Always close the FileInputStream object when you’re finished with it.
Advantages of using the BufferedInputStream class in Java
Example 2: Java program to show skip method
import java.io.FileInputStream; public class Main { public static void main (String args[]) { try { FileInputStream input = new FileInputStream ("input.txt"); // Skips the first 5 bytes input.skip (5); System.out.println ("Input stream after skipping 5 bytes:"); // Reads and prints the remaining bytes in the file int i = input.read (); while (i != -1) { System.out.print ((char) i); // Reads next byte from the file i = input.read (); } // Close the file input stream input.close (); } catch (Exception e) { e.getStackTrace (); } } }
Output
Input stream after skipping 5 bytes: is is a line of text inside the file.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment