You are here:   HomeJava ProgrammingStreamFileInputStream in Java Example
by Dinesh Thakur Category: Stream

We use FilelnputStream class for reading from the file as it creates an input byte stream for reading from the file. To read the contents from the file ecomputernotes.bat, we first make an object by name say fp of FileOutputStream class and specify the file name ecomputernotes.bat as an argument to the constructor:

fp=new FilelnputStream(ecomputernotes.bat ");

If the file is not found or some error occurs in the disk, then the exception FileNotFoundException is thrown. If the file is found and everything is well, the matter is read from the file and is displayed on the screen after casting it into characters (because data in file is in byte form). When file is over, it is closed by fp.close() method.

import java.io.*;

class FileInputStreamJavaExample
{
      public static void main(String args[]) throws IOException
      {
            int i;
            FileInputStream fp;
            try
             {
                 fp=new FileInputStream("ecomputernotes.bat");
             }
                  catch(FileNotFoundException e)
                  {
                      System.out.println("File Cannot be Found");
                      return;
                  }
                     System.out.println("Data in File is");
                    do
                      {
                          i=fp.read();
                          if(i !=-1)
                          System.out.print((char)i);
                      }while(i !=-1);
                         fp.close();
       }
 }   

FileInputStream





Subscribe To Free Daily Newsletter!

Get Free News Updates Delivered Directly To Your Inbox
About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to contact us.



What's New and Popular





Popular Article