Home » Java FileInputStream Class

Java FileInputStream Class

by Online Tutorials Library

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:


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

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 Tutor Aspire. 

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

Output:

Welcome to Tutor Aspire 

You may also like