Read file using FileInputStream - Java Program

Q. Write a program to read the data from the file using FileInputStream.

Answer:

FileInputStream class is used to read the data from the file. it should be used to read byte-oriented data for example read image, audio, video.

In this example, we read the data from a text file "test.txt" and print the ASCII value of each character. The printStackTrace() method is used to print error message.

//test.txt
Welcome

FileInputStreamTest.java

import java.io.*;
public class FileInputStreamTest
{
     public static void main(String args[])
     {
          try
          {
               FileInputStream fis = new FileInputStream("test.txt");
               int i;
               System.out.println("ASCII value of the character:");
               while((i=fis.read()) != -1)
               {
                    System.out.print(i+" : ");
                    System.out.println((char)i);
               }
          }
          catch (FileNotFoundException fnfe)
          {
               fnfe.printStackTrace();
          }
          catch (IOException io)
          {
               io.printStackTrace();
          }
     }
}


Output:

fileinputstream