Open In App

Java FileInputStream Class

Last Updated : 11 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

FileInputStream class in Java is useful for reading data from a file in the form of a Java sequence of bytes. FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.

Example: FileInputStream class to read data from file.

import java.io.*;

public class Geeks {

    public static void main(String[] args)
    {

        // Use try-with-resources to handle resource
        // management
        try (FileInputStream fi
             = new FileInputStream("file1.txt")) {

            // Illustrating getChannel() method
            System.out.println("Channel: "
                               + fi.getChannel());

            // Illustrating getFD() method
            System.out.println("File Descriptor: "
                               + fi.getFD());

            // Illustrating available method
            System.out.println("Number of remaining bytes: "
                               + fi.available());

            // Illustrating skip() method
            fi.skip(4);

            System.out.println("File Contents:");

            // Reading characters from FileInputStream
            int ch;
            while ((ch = fi.read()) != -1) {
                System.out.print((char)ch);
            }
        }
        catch (FileNotFoundException e) {
            System.out.println(
                "File not found: Ensure 'file1.txt' exists in the working directory.");
        }
        catch (IOException e) {
            System.out.println(
                "An error occurred while reading the file: "
                + e.getMessage());
        }
    }
}

Output: 

Screenshot


Declaration

Class declaration of FileInputStream is given below:

public class FileInputStream extends InputStream

Note: FileInputStream is a subclass of InputStream, which is used for reading bytes from a file.

Constructors of FileInputStream Class

1. FileInputStream(String name)

Creates an input file stream to read from a file with the specified name. 

Example:

FileInputStream fi = new FileInputStream(“example.txt”);

2. FileInputStream(File file)

Creates an input file stream to read from the specified File object. 

Example:

File f = new File(“example.txt”);

FileInputStream fi = new FileInputStream(f);

3. FileInputStream(FileDescriptor fdobj)

Creates an input file stream to read from the specified file descriptor. 

Example:

FileDescriptor fd = FileDescriptor.in;

FileInputStream fi = new FileInputStream(fd); 

Methods of Java FileInputStream Class

Methods Action Performed 
available()Returns an estimate of the number of remaining bytes that can be read (or skipped over) from this input stream.
close()Closes this file input stream and releases any system resources associated with the stream.
finalize()Ensures that the close method of this file input stream is called when there are no more references to it. 
getChannel()Returns the unique FileChannel object associated with this file input stream. 
getFD()Returns the FileDescriptor object that represents the connection to the actual file in the file system being used by this FileInputStream.
read()Reads a byte of data from this input stream
read(byte[] b)Reads up to b.length bytes of data from this input stream into an array of bytes. 
read(byte[] b, int off, int len)Reads up to len bytes of data from this input stream into an array of bytes.
skip()Skips over and discards n bytes of data from the input stream

Steps to Read Data using FileInputStream

Following steps are typically followed to read data from the file.

Step 1: Attach a file to a FileInputStream

This step will enable us to read data from the file as shown below as follows

FileInputStream fi =new FileInputStream(“file.txt”);

Step 2: Use read() method to read data

Use the read() method of FileInputStream to read bytes of data from the file.

int ch = fileInputStream.read();

Step 3-A: Check for End of File

When there is no more data available to read further, the read() method returns -1; 

Step 3-B: Print the Data

Convert the integer value returned by read() into character (using(char)) and then print it.

System.out.print((char) ch);

Example: Read Data from a File Using FileInputStream

Here’s an implementation of the steps discussed above to read the contents of a file and display it.

Note: To ensure the program runs correctly, create a file named file.txt in the working directory. Once the working directory is determined, create the file file.txt in that location. Add the following content to the file:

this is my first code

this is my second code

Save the file and run the program. The program will read and display the contents of file.txt as output.

Example:

// Java Program to Demonstrate the working of
// FileInputStream Class
import java.io.*;

public class Geeks {

    public static void main(String args[])
    {
        try {
          
            // Attach a file to FileInputStream
            FileInputStream fi
                = new FileInputStream("file.txt");

            // Read data from FileInputStream
            int ch;
            while ((ch = fi.read()) != -1) {
              
                // Print the data
                System.out.print((char)ch);
            }

            // Close the stream
            fi.close();
        }
        catch (FileNotFoundException e) {
            System.out.println(
                "File not found: Ensure the file exists.");
        }
        catch (IOException e) {
            System.out.println(
                "An error occurred while reading the file.");
        }
    }
}

Output: 

Output

Key Features of FileInputStream

  • Byte Oriented Stream: It reads data in the form of bytes
  • Direct Access: It directly reads the file content from the disk without buffering
  • Platform Independent: It can work on any operating system


Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg