Java FileInputStream Class

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 example 1: read single character

  1. import java.io.FileInputStream;  
  2. public class DataStreamExample {  
  3.      public static void main(String args[]){    
  4.           try{    
  5.             FileInputStream fin=new FileInputStream("testout.txt");    
  6.             int i=fin.read();  
  7.             System.out.print((char)i);    
  8.   
  9.             fin.close();    
  10.           }catch(Exception e){System.out.println(e);}    
  11.          }    
  12.         }  
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 java .
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

  1.   
  2.   
  3. import java.io.FileInputStream;  
  4. public class DataStreamExample {  
  5.      public static void main(String args[]){    
  6.           try{    
  7.             FileInputStream fin=new FileInputStream("testout.txt");    
  8.             int i=0;    
  9.             while((i=fin.read())!=-1){    
  10.              System.out.print((char)i);    
  11.             }    
  12.             fin.close();    
  13.           }catch(Exception e){System.out.println(e);}    
  14.          }    
  15.         }  
Previous
Next Post »