Java FileInputStream Example

The FileInputStream class creates an InputStream that you can use to read bytes from a file. It is used for reading byte-oriented data (streams of raw bytes) such as image data, audio, video, etc. 

FileInputStream Class Example

In this example demonstrate the usage of few important methods of FileInputStream class.
This example shows how to read a single byte, an array of bytes, and a subrange of an array of bytes. It also illustrates how to use available( ) to determine the number of bytes remaining and how to use the skip( ) method to skip over unwanted bytes.
The program reads its own source file, which must be in the current directory.
Notice that it uses the try-with-resources statement to automatically close the file when it is no longer needed.
import java.io.FileInputStream;
import java.io.IOException;

/**
 * The class demonstrate the usage of FileInputStream class methods.
 * @author javaguides.net
 *
 */

public class FileInputStreamDemo {
 public static void main(String args[]) {
  int size;
  // Use try-with-resources to close the stream.
  try (FileInputStream f = new FileInputStream("FileInputStreamDemo.java")) {

   System.out.println("Total Available Bytes: " + (size = f.available()));

   int n = size / 40;
   System.out.println("First " + n + " bytes of the file one read() at a time");
   for (int i = 0; i < n; i++) {
    System.out.print((char) f.read());
   }

   System.out.println("\nStill Available: " + f.available());
   System.out.println("Reading the next " + n + " with one read(b[])");
   byte b[] = new byte[n];
   if (f.read(b) != n) {
    System.err.println("couldn’t read " + n + " bytes.");
   }

   System.out.println(new String(b, 0, n));
   System.out.println("\nStill Available: " + (size = f.available()));

   System.out.println("Skipping half of remaining bytes with skip()");
   f.skip(size / 2);

   System.out.println("Still Available: " + f.available());
   System.out.println("Reading " + n / 2 + " into the end of array");

   if (f.read(b, n / 2, n / 2) != n / 2) {
    System.err.println("couldn’t read " + n / 2 + " bytes.");
   }
   System.out.println(new String(b, 0, b.length));
   System.out.println("\nStill Available: " + f.available());
  } catch (IOException e) {
   System.out.println("I/O Error: " + e);
  }
 }
}
Output:
Total Available Bytes: 1523
First 38 bytes of the file one read() at a time
package com.javaguides.javaio.book;

Still Available: 1485
Reading the next 38 with one read(b[])

import java.io.FileInputStream;
impo

Still Available: 1447
Skipping half of remaining bytes with skip()
Still Available: 724
Reading 19 into the end of array

import java.io.Filrintln("couldn’t re

Still Available: 705

Reference

Comments