FileInputStream in Java


File FileInputStream JavaViews 2163

FileInputStream in Java

The FileInputStream class in Java extends the InputStream class. We use this class to read data in the form of bytes from a file. For example, we can use the FileInputStream to read an image, pdf file, audio, video.

Hierarchy

FileInputStream in Java

Constructors

The FileInputStream in Java has the below constructors:

ConstructorDescription
FileInputStream(File f)Creates an input file stream to read data from the specified file.
FileInputStream(FileDescriptor fd)Creates a file input stream to read the specified file descriptor
FileInputStream(String name)Creates an input file stream to read data from a file specified with name

Java FileInputStream methods

MethodDescription
int available()Returns an estimate of the number of available bytes to read from the file
void close()Closes the specified file
FileChannel getChannel()Returns the unique FileChannel associated with the specified file
FileDescriptor getFD()Returns the FileDescriptor associated to connect with the specified file
void mark(int readLimit)Marks the current position in the input file
boolean markSupported()Checks if the file supports mark() and reset() methods.
int read()Reads a byte of data from the input stream
int read(byte[] b)Reads upto b.length bytes of data from the file
int read(byte[] b, int off, int len)Reads upto len bytes of data from the offset from the input stream
byte[] readAllBytes()Reads all the remaining bytes of data from the input stream
byte[] readNBytes(int len)Reads upto specified number of bytes from the input stream
int readNBytes(byte[] b, int off, int len)Reads upto the specified number of bytes from the input stream
long skip(long n)Skips and discards the n number of bytes from the input stream
void skipNBytes(long n)Skips and discards exactly n number of bytes from the input stream.
long transferTo(OutputStream out)Reads and writes all bytes of data from the InputStream to the OutputStream in the same order it reads

Example: Read a single character from the file

The below example shows how to read a single character from the input file. We can use the read() method of the FileInputStream class which reads a single character at a time. To print it, we can typecast the value to char. Since the input file contains the content “Java programming”, it prints the first character “J” as the output.

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

public class ReadFile {

  public static void main(String[] args) throws IOException {
    try {
      FileInputStream fi = new FileInputStream("InputFile.txt");
      int a = fi.read();
      System.out.println((char)a);
      fi.close();
      
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
    
  }

}
J

Content in the input file

InputFile

Example: Read all characters from the file

In the below example, we are reading all characters from the input file using the read() method. Every time we call the read() method, it reads a single character. Hence using the while loop, we can read the data until this method returns -1 which is the end of the file.

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

public class ReadFile {

  public static void main(String[] args) throws IOException {
    try {
      FileInputStream fi = new FileInputStream("InputFile.txt");
      int a = 0;
      while((a=fi.read()) != -1)
        System.out.print((char)a);
      fi.close();
      
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
    
  }

}
Java programming

Example: available() method

The below example shows the working of the available() method before and after the read() operation. Since we are reading 4 characters, the number of bytes remaining is reduced by 4.

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

public class CheckAvailableBytes {

  public static void main(String[] args) throws IOException {
    FileInputStream fi = new FileInputStream("InputFile.txt");
    int a = 0;
    
    System.out.println("Available bytes before read operation: " + fi.available());
    System.out.print((char)fi.read());
    System.out.print((char)fi.read());
    System.out.print((char)fi.read());
    System.out.print((char)fi.read());
    
    System.out.println("\nAvailable bytes after read operation: " + fi.available());
    fi.close();

  }

}
Available bytes before read operation: 16
Java
Available bytes after read operation: 12

Example: skip() method

We can skip the specified number of bytes and read the remaining contents from the FileInputStream using the skip() method. The below example skips 4 bytes and prints the remaining information. The input file contains the information “Java programming”. Hence after skipping 4 bytes of data, it prints only ” programming”.

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

public class SkipDemo {

  public static void main(String[] args) throws FileNotFoundException {
    FileInputStream fi = new FileInputStream("InputFile.txt");
    
    try {
      fi.skip(4);
      System.out.println("Contents after skipping 4 bytes:");
      int a = 0;
      while((a=fi.read()) != -1)
        System.out.print((char)a);
      fi.close();
      
    } catch (IOException e) {
      e.printStackTrace();
    }
    

  }

}
Contents after skipping 4 bytes:
 programming

Example: FileDescriptor getFD() method

The getFD() method of the FileInputStream class in Java returns the FileDescriptor object that establishes the connection to the file. The below example checks if the file is valid or not using the valid() method of the FileDescriptor.

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

public class FileDescriptorDemo {

  public static void main(String[] args) throws IOException {
    FileInputStream fi = new FileInputStream("InputFile.txt");
    FileDescriptor fd = fi.getFD();
    System.out.println("Valid file: " + fd.valid());
  }

}
Valid file: true

Example: FileChannel getChannel() method

The below example shows how to retrieve the current position using the getChannel() method. As and when we read a character using the read() method, the position increments by 1.

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.channels.FileChannel;

public class FileChannelDemo {

  public static void main(String[] args) throws IOException {
    try {
      FileInputStream fi = new FileInputStream("InputFile.txt");
      System.out.println("Number of available bytes: " + fi.available());
      int a;
      while((a=fi.read()) != -1) {
        FileChannel fc = fi.getChannel();
        System.out.print("Current position: " + fc.position());
        System.out.println("\tCharacter: " + (char)a);
      }			
      fi.close();
      
      
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }	

  }

}
Number of available bytes: 16
Current position: 1	Character: J
Current position: 2	Character: a
Current position: 3	Character: v
Current position: 4	Character: a
Current position: 5	Character:  
Current position: 6	Character: p
Current position: 7	Character: r
Current position: 8	Character: o
Current position: 9	Character: g
Current position: 10	Character: r
Current position: 11	Character: a
Current position: 12	Character: m
Current position: 13	Character: m
Current position: 14	Character: i
Current position: 15	Character: n
Current position: 16	Character: g

Example: Read specific number of characters

In the below example, the input file contains the text “Java programming”. We can read specific characters using the read() method where we can specify the starting position as the offset parameter and the number of characters to read as the length. In this example, offset is 0 and length is 6 which means it reads the characters from the position 0 up to 6 characters. Since the capacity is 12, it fills the remaining 6 bytes as *.

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

public class ReadSpecificCharacters {

  public static void main(String[] args) throws IOException {
    try {
      FileInputStream fi = new FileInputStream("InputFile.txt");
      byte[] b = new byte[12];
      int a = fi.read(b, 0, 6);
      System.out.println("Total number of bytes: "+ fi.available());
      System.out.println("Number of bytes read: " + a);
      
      for(byte by : b) {
        char ch = (char)by;
        if(by == 0)
          ch = '*';
        System.out.print(ch);
      }
        
      fi.close();
      
      
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
    

  }

}
Total number of bytes: 10
Number of bytes read: 6
Java p******

 

Reference

Translate ยป