How to read data from a file using FileInputStream?


The FileInputStream class reads the data from a specific file (byte by byte). It is usually used to read the contents of a file with raw bytes, such as images.

To read the contents of a file using this class −

  • First of all, you need to instantiate this class by passing a String variable or a File object, representing the path of the file to be read.
FileInputStream inputStream = new FileInputStream("file_path");
or,
File file = new File("file_path");
FileInputStream inputStream = new FileInputStream(file);
  • Then read the contents of the specified file using either of the variants of read() method −
    • int read() − This simply reads data from the current InputStream and returns the read data byte by byte (in integer format).

      This method returns -1 if the end of the file is reached.

    • int read(byte[] b) − This method accepts a byte array as parameter and reads the contents of the current InputStream, to the given array.

      This method returns an integer representing the total number of bytes or, -1 if the end of the file is reached.

    • int read(byte[] b, int off, int len) − This method accepts a byte array, its offset (int) and, its length (int) as parameters and reads the contents of the current InputStream, to the given array.
    • This method returns an integer representing the total number of bytes or, -1 if the end of the file is reached.

Example

Assume we have the following image in the directory D:/images

Following program reads contents of the above image using the FileInputStream.

Example

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class FileInputStreamExample {
   public static void main(String args[]) throws IOException {
      //Creating a File object
      File file = new File("D:/images/javafx.jpg");
      //Creating a FileInputStream object
      FileInputStream inputStream = new FileInputStream(file);
      //Creating a byte array
      byte bytes[] = new byte[(int) file.length()];
      //Reading data into the byte array
      int numOfBytes = inputStream.read(bytes);
      System.out.println("Data copied successfully...");
   }
}

Output

Data copied successfully...
raja
Published on 01-Aug-2019 17:18:45
Advertisements