FileInputStream in Java | Methods, Example

FileInputStream in Java is the most basic file input stream class that is designed to read bytes from a file.

In simple words, it reads data from a text file in the form sequence of bytes. That is, it inputs a stream of bytes from a file.

FileInputStream was introduced in Java 1.0 version. It is present in java.io.FileInputStream package.

FileInputStream Class


FileInputStream class is derived from InputStream that is abstract superclass of FileInputStream. It implements Closeable and AutoCloseable interfaces.

The general syntax for FileInputStream class is as follows:

public class FileInputStream
  extends InputStream
     implements Closeable, AutoCloseable

Constructor of FileInputStream class in Java


FileInputStream class defines the following constructors that create an InputStream and read bytes from a file. Its two most common constructors are as follows:

1. FileInputStream(File file): This constructor creates a FileInputStream from a File object in the file system.

2. FileInputStream(FileDescriptor fdObj): This form of constructor creates a FileInputStream by using the file descriptor fdObj.

3. FileInputStream(String filename): This form of constructor constructs a FileInputStream from a file name.

If we try to create a FileInputStream with a nonexistent file, java.io.FileNotFoundException will occur.

Steps to Read Data from File using FileInputStream class


There are the following steps to read data from a text file using FileInputStream that are as follows:

1. First, we need to add a file to a FileInputStream as follows:

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

This FileInputStream object enables us to read data from a file in the form of bytes.

2. Next step is to read data from a file. We need to call read() method using the file input stream object reference variable. The syntax is as follows:

chars = fis.read();

Once the read() method reads all the characters from a file, it will reach the end of the file, and -1 will be returned if there is no more data available to read further.


Look at the below figure to understand two steps for reading data from a text file using Java FileInputStream class.

Steps to read data using FileInputStream class in Java

Methods of FileInputStream class in Java


FileInputStream class does not define any new methods. All the methods in this class are inherited from InputStream. The most common inherited methods from InputStream are as follows:

1. int available(): This method is used to get the number of bytes that can be read (or skipped over) from this file input stream without blocking by the next invocation of a method for this input stream.

2. void close(): This method closes the file input stream and releases any system resources associated with the stream.

3. FileDescriptor getFD(): This method returns the FileDescriptor object that represents the association to the actual file in the file system being used by this FileInputStream.

4. int read(): This method reads a byte of data from the input stream.


5. int read(byte[ ] b): This method reads up to b.length bytes of data from the invoking input stream into an array of bytes.

6. int read(byte[ ] b, int n, int m): It reads up to m bytes of data from this input stream into an array of bytes from the nth byte.

7. long skip(long n): This method skips over and discards n bytes of data from the input stream.

Almost all the methods in the I/O stream classes throw an exception named IOException. This exception is thrown when an Input/Output operation fails because of an interrupted call.

Therefore, we need to declare to throw java.io.IOException in the method or put the code in a try-catch block, as shown below:

Declaring IOException exception in the method
public static void main(String[] args) throws IOException
{
   // Perform I/O operations.
}
or,

Using try-catch block
public static void main(String[] args) 
{
try {
   // Perform I/O operations
}
catch (IOException ex) {
    ex.printStackTrace();
}

Example Program based on Java FileInputStream


1. Let’s take an example program where we will read data from myfile.txt using FileInputStream and display it on the monitor. Before doing coding, first, create a file named myfile.txt.


In this file, we will get the following content: Welcome to Scientech Easy.

We will write code to read a single character only from this file. Look at the source code to understand better.

Program source code 1: Reading a single character

package javaProgram;
import java.io.FileInputStream;
public class ReadFile {
public static void main(String[] args)
{
try {  
// Attach a file to FileInputStream for reading data and create an input stream for a file	
    FileInputStream fis = new FileInputStream("D:\\myfile.txt"); 
 
// Reading a value from a file in the form of byte. 
     int value = fis.read(); 
     System.out.println("Reading a value in byte form: " +value);
   
// Converting byte into character to see text.   
     System.out.print((char)value); // Displaying a single character on console.  

      fis.close(); // Closing input stream automatically.   
} catch(Exception e){
          System.out.println(e);
 }   
 }
}
Output:
      Reading a value in byte form: 87
      W

After executing the preceding program, you will get a value 87 (in byte form) and a single character from the file. To see the read text, we need to translate it into character.

The java.io.InputStream class implements AutoClosable interface. The AutoClosable interface defines the close() method that closes a resource automatically.

Note: When a stream is no longer required, always close it using the close() method or automatically close it using a try-with-resource statement.

Not closing streams may produce data corruption in the output file or other programming errors.

2. Let’s take an example program where we will read all byte values from a file and display them on the console.

Program source code 2:

package javaProgram;
import java.io.FileInputStream;
public class ReadFile {
public static void main(String[] args)
{
try {  
  FileInputStream fis = new FileInputStream("D:\\myfile.txt"); 
 
// Reading all byte values from a file and display on the console. 
     int value = 0;    
     while((value = fis.read())!=-1)
     {    
       System.out.print(value + " ");
      }    
    fis.close();    
  } catch(Exception e){
           System.out.println(e);
  } 
 }
}
Output:
       87 101 108 99 111 109 101 32 116 111 32 83 99 105 101 110 116 101 99 104 32 69 97 115 121

In this example program, values are read from the file and displayed on the console in lines. The expression ((value = fis.read()) != -1) reads a byte from fis.read(), assigns it to value, and checks whether it is –1. The input value of –1 represents the end of a file.

Program source code 3: Reading all characters from a file

package javaProgram;
import java.io.FileInputStream;
public class ReadFile {
public static void main(String[] args)
{
try {  
  FileInputStream fis = new FileInputStream("D:\\myfile.txt"); 
 
 int value = 0;    
 while((value = fis.read())!=-1)
 {    
     System.out.print((char)value);
 }    
fis.close();    
} catch(Exception e){
  System.out.println(e);
 } 
 }
}
Output:
      Welcome to Scientech Easy

3. Let’s create a program where we will see how to read a single byte, an array of bytes, and a subrange array of bytes. We will also determine the number of available bytes remaining using available() method and skip unwanted bytes by using skip() method.

Look at the source code and try to understand it one by one.

Program source code 4:

package javaProgram;
import java.io.FileInputStream;
import java.io.IOException;
public class ReadFile {
public static void main(String[ ] args) throws IOException
{
 FileInputStream fis = new FileInputStream("D:\\myfile.txt"); 
 int size = fis.available();
 
 System.out.println("Total number of available bytes: " +size);
 int n = size/10; // n = 2.
 
  for (int i = 0; i < n; i++) {
      System.out.print((char) fis.read()); // Reading the first two characters W and e.
 }
System.out.println("\nStill Available bytes: " + fis.available());
byte bytearray[ ] = new byte[2];

if (fis.read(bytearray) != n) {
 System.out.println("Could not get" + n + "bytes");
}
String str = new String(bytearray, 0, n);
System.out.println(str);

System.out.println("\nStill available bytes: " +fis.available());
System.out.println("\nSkipping half of remaining bytes using skip() method");
 fis.skip(size/2);

System.out.println("Still Available bytes: " + fis.available());

System.out.println("Reading " + n/2 + " from the end of array");
if (fis.read(bytearray, n/2, n/2) != n/2) {
  System.out.println("couldn't read " + n/2 + " bytes.");
}
String str2 = new String(bytearray, 0, bytearray.length);
System.out.println(str2);

System.out.println("\nStill Available bytes: " + fis.available());
 fis.close();
 }
}
Output:
       Total number of available bytes: 25
       We
       Still Available bytes: 23
       lc

       Still available bytes: 21

       Skipping half of remaining bytes using skip() method
       Still Available bytes: 9
       Reading 1 from the end of array
       lt
       Still Available bytes: 8

This example program somewhat contrived demonstrates how to read data in three ways, skip input, and inspect the amount of data available on a stream.


Hope that this tutorial has covered almost all the important points concerning FileInputStream class in Java with example programs. I hope that you will have understood the steps to read data using file input stream class.
Thanks for reading!!!
Next ⇒ FileOutputStream Class in Java

⇐ Prev Next ⇒