Java Fileinputstream Class

The Java FileInputStream class is utilized to fetch input bytes from a file, primarily for processing byte-oriented data like image, audio, and video files. It can also be employed to read character-stream data, although it is advisable to use the FileReader class for reading streams of characters.

Java FileInputStream Class Declaration

Let's examine the syntax for the java.io.FileInputStream class declaration:

Example

public class FileInputStream extends InputStream

Java FileInputStream Class Methods

Method Description
int available() It is used to return the estimated number of bytes that can be read from the input stream.
int read() It is used to read the byte of data from the input stream.
int read(byte[] b) It is used to read up tob.lengthbytes of data from the input stream.
int read(byte[] b, int off, int len) It is used to read up tolenbytes of data from the input stream.
long skip(long x) It is used to skip over and discards x bytes of data from the input stream.
FileChannel getChannel() It is used to return the unique FileChannel object associated with the file input stream.
FileDescriptor getFD() It is used to return theFileDescriptorobject.
protected void finalize() It is used to ensure that the close method is call when there is no more reference to the file input stream.
void close() It is used to closes thestream.

Java FileInputStream Example 1: Read Single Character

File Name: DataStreamExample.java

Example

import java.io.FileInputStream;

public class DataStreamExample {

	 public static void main(String args[]){  

		  try{  

		    FileInputStream fin=new FileInputStream("D:\\testout.txt");  

		    int i=fin.read();

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



		    fin.close();  

		  }catch(Exception e){System.out.println(e);}  

		 }  

		}

Note: Before running the code, a text file named as "testout.txt" is required to be created. In this file, we have written the following content in the file:

Example

Welcome to hello world.

Upon running the program provided, a solitary character will be extracted from the file, represented by the byte value of 87. To display this as text, it must be converted into its corresponding character.

Output:

Java FileInputStream Example 2: Read All Characters

File Name: DataStreamExample.java

Example

package com.example;



import java.io.FileInputStream;

public class DataStreamExample {

	 public static void main(String args[]){  

		  try{  

		    FileInputStream fin=new FileInputStream("D:\\testout.txt");  

		    int i=0;  

		    while((i=fin.read())!=-1){  

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

		    }  

		    fin.close();  

		  }catch(Exception e){System.out.println(e);}  

		 }  

		}

Output:

Output

Welcome to Java

FileInputStream Class Constructors

The Java FileInputStream class offers multiple constructors for creating an instance of a FileInputStream, enabling the reading of bytes from a file through different approaches. Below are the constructors provided by the FileInputStream class:

1. FileInputStream(String name)

An instance of FileInputStream is established by initiating a connection to a real file, identified by the specified path in the filesystem.

  • Input: name - the file's name.
  • Exception: FileNotFoundException is thrown when the file is not found, is a directory instead of a standard file, or encounters issues preventing it from being opened for reading.

Example:

Example

FileInputStream fis = new FileInputStream("example.txt");

File Name: FileInputStreamExample.java

Example

import java.io.FileInputStream;

import java.io.IOException;

public class FileInputStreamExample {

    public static void main(String[] args) {

        // Specify the file name to open

        String fileName = "D:\\hello world\\April\\Files\\example.txt";

        // Try-with-resources statement to ensure the FileInputStream is closed after

        // use

        try (FileInputStream fis = new FileInputStream(fileName)) {

            int i;

            // Read one byte at a time until the end of the file is reached

            while ((i = fis.read()) != -1) {

                // Convert the byte to a char and print it

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

            }

        } catch (IOException e) {

            // Handle exceptions, such as FileNotFoundException

            e.printStackTrace();

        }

    }

}

Output:

2. FileInputStream(File file)

A FileInputStream is established by initiating a connection to a physical file indicated by a File object.

  • Input: file - the File object indicating the file to be accessed.
  • In case the file is inaccessible, not a standard file, or encounters any other obstacle preventing reading, a FileNotFoundException is thrown.

Example:

Example

File file = new File("example.txt");

FileInputStream fis = new FileInputStream(file);

File Name: FileInputStreamExample.java

Example

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

public class FileInputStreamExample {

    public static void main(String[] args) {

        // Create a File object for the file to be read

        File file = new File("D:\\hello world\\April\\Files\\example.txt");

        // Try-with-resources statement to ensure the FileInputStream is closed after

        // use

        try (FileInputStream fis = new FileInputStream(file)) {

            int i;

            // Read one byte at a time until the end of the file is reached

            while ((i = fis.read()) != -1) {

                // Convert the byte to a char and print it

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

            }

        } catch (IOException e) {

            // Handle exceptions, such as FileNotFoundException

            e.printStackTrace();

        }

    }

}

Output:

3. FileInputStream(FileDescriptor fdObj)

An instance of FileInputStream is generated through the utilization of a file descriptor called fdObj, which signifies an established link to a real file within the file system.

  • Input: fdObj - denoting the file descriptor.
  • Tip: This approach is valuable in scenarios where a FileDescriptor for a file is available, potentially acquired from another file system task or through inter-process communication.

Example:

Example

FileDescriptor fd = FileDescriptor.in; // Just an example, usually you get it from other sources.

FileInputStream fis = new FileInputStream(fd);

File Name: FileDescriptorExample.java

Example

import java.io.File;

import java.io.FileDescriptor;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

public class FileDescriptorExample {

    public static void main(String[] args) {

        // Specify the file path

        String filePath = "example.txt";

        // Create a file and write some data to it

        try (FileOutputStream out = new FileOutputStream(filePath)) {

            out.write("Hello, world!".getBytes());

        } catch (IOException e) {

            System.out.println("Error writing to file: " + e.getMessage());

            return;

        }

        // Read from the file using FileInputStream and FileDescriptor

        try (FileInputStream fis = new FileInputStream(filePath);

                FileInputStream fisFromFD = new FileInputStream(fis.getFD())) {

            // Read data from the FileInputStream

            int data;

            while ((data = fisFromFD.read()) != -1) {

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

            }

        } catch (IOException e) {

            System.out.println("Error reading from file: " + e.getMessage());

        }

    }

}

Output:

Output

Hello, world!

The script is designed to generate a new file named sample.txt, input the text "Greetings, Earth!" into it, and subsequently retrieve the content using a FileDescriptor to showcase the practical application of this Java functionality. Modify the file location and settings as required. This self-contained instance is ideal for grasping the collaborative functionality of FileInputStream and FileDescriptor in real-world scenarios.

Input Required

This code uses input(). Please provide values below: