Java – FileInputStream Class

Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data (streams of raw bytes) such as image data, audio, video etc. You can also read character-stream data. But, for reading streams of characters, it is recommended to use FileReader class.


Java FileInputStream class declaration

Let’s see the declaration for java.io.FileInputStream class:

  1. public class FileInputStream extends InputStream

Java FileInputStream class methods

Method Description
int available() It is used to return the estimated number of bytes that can be read from the input stream.
int read() It is used to read the byte of data from the input stream.
int read(byte[] b) It is used to read up to b.length bytes of data from the input stream.
int read(byte[] b, int off, int len) It is used to read up to len bytes of data from the input stream.
long skip(long x) It is used to skip over and discards x bytes of data from the input stream.
FileChannel getChannel() It is used to return the unique FileChannel object associated with the file input stream.
FileDescriptor getFD() It is used to return the FileDescriptor object.
protected void finalize() It is used to ensure that the close method is call when there is no more reference to the file input stream.
void close() It is used to closes the stream.

 

Java FileInputStream example 1: read single character

package io.inputstream;

import java.io.FileInputStream;

public class DataStreamExample {
    public static void main(String args[]) {
        try {
            FileInputStream fin = new FileInputStream("D:\\testout.txt");
            int i = fin.read();
            System.out.print((char) i);

            fin.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

Note: Before running the code, a text file named as “testout.txt” is required to be created. In this file, we are having following content:

Welcome to javatpoint.

After executing the above program, you will get a single character from the file which is 87 (in byte form). To see the text, you need to convert it into character.

Output:

W

Java FileInputStream example 2: read all characters

package io.inputstream;


import java.io.FileInputStream;

public class DataStreamExample2 {
    public static void main(String args[]) {
        try {
            FileInputStream fin = new FileInputStream("D:\\testout.txt");
            int i = 0;
            while ((i = fin.read()) != -1) {
                System.out.print((char) i);
            }
            fin.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

Output:

Welcome to javaTpoint

Leave a Reply

Your email address will not be published. Required fields are marked *