Skip to Content

Read file using FileInputStream

  1. /*
  2.   Read file using FileInputStream
  3.   This example shows how to read a file using Java FileInputStream class.
  4.   FileInputStream is used to read binary content of the file and
  5.   return bytes of data.
  6. */
  7. import java.io.*;
  8.  
  9. public class ReadStringFromFile {
  10.  
  11.   public static void main(String[] args) {
  12.    
  13.     //create file object
  14.     File file = new File("C://FileIO//ReadString.txt");
  15.    
  16.     int ch;
  17.     StringBuffer strContent = new StringBuffer("");
  18.     FileInputStream fin = null;
  19.    
  20.     try
  21.     {
  22.       /*
  23.        * Create new FileInputStream object. Constructor of FileInputStream throws
  24.        * FileNotFoundException if the agrument File does not exist.
  25.        */
  26.      
  27.       fin = new FileInputStream(file);
  28.      
  29.       /*
  30.        * To read bytes from stream use,
  31.        * int read() method of FileInputStream class.
  32.        *
  33.        * This method reads a byte from stream. This method returns next byte of data
  34.        * from file or -1 if the end of the file is reached.
  35.        *
  36.        * Read method throws IOException in case of any IO errors.
  37.        */
  38.      
  39.       while( (ch = fin.read()) != -1)
  40.         strContent.append((char)ch);
  41.  
  42.       /*
  43.        * To close the FileInputStream, use
  44.        * void close() method of FileInputStream class.
  45.        *
  46.        * close method also throws IOException.
  47.        */
  48.       fin.close();
  49.      
  50.     }
  51.     catch(FileNotFoundException e)
  52.     {
  53.       System.out.println("File " + file.getAbsolutePath() +
  54.                              " could not be found on filesystem");
  55.     }
  56.     catch(IOException ioe)
  57.     {
  58.       System.out.println("Exception while reading the file" + ioe);
  59.     }
  60.    
  61.     System.out.println("File contents :");
  62.     System.out.println(strContent);
  63.    
  64.    
  65.     /*
  66.      * Please note that, FileInputStream SHOULD NOT BE USED to read
  67.      * character data file.
  68.      * It is meant for reading binary data such as an image file.
  69.      *
  70.      * To read character data, FileReader should be used.
  71.      */
  72.   }
  73. }
  74.  
  75. /*
  76. Output would be
  77. File contents :
  78. This file is a demonstration of how to read a file using Java FileInputStream.
  79. */