Java FileInputStream class

Introduction

The FileInputStream class extends InputStream to read bytes from a file.

Two commonly used constructors are shown here:

FileInputStream(String filePath )  
FileInputStream(File fileObj ) 

The following example creates two FileInputStream classes that use the same disk file:

FileInputStream f0 = new FileInputStream("/Main.java")  

File f = new File("/Main.java");  
FileInputStream f1 = new FileInputStream(f); 

The next example shows how to read a text file using Java FileInputStream class.

import java.io.FileInputStream;
import java.io.IOException;

public class Main {
  public static void main(String args[]) {
    int size;/*from  w w  w .j a va2  s.c  o m*/

    // Use try-with-resources to close the stream.
    try (FileInputStream f = new FileInputStream("Main.java")) {

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

      int n = 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);
    }
  }
}



PreviousNext

Related