Skip to Content

Read file in byte array using FileInputStream

  1. /*
  2.   Read file in byte array using FileInputStream
  3.   This example shows how to read a file in byte array using Java FileInputStream
  4.   class. This method should only be used when the file size is less
  5.   than Integer.MAX_VALUE.
  6. */
  7.  
  8. import java.io.*;
  9.  
  10. public class ReadFileByteArray {
  11.  
  12.   public static void main(String[] args) {
  13.    
  14.     //create file object
  15.     File file = new File("C://FileIO//ReadString.txt");
  16.    
  17.     try
  18.     {
  19.       //create FileInputStream object
  20.       FileInputStream fin = new FileInputStream(file);
  21.      
  22.       /*
  23.        * Create byte array large enough to hold the content of the file.
  24.        * Use File.length to determine size of the file in bytes.
  25.        */
  26.      
  27.      
  28.        byte fileContent[] = new byte[(int)file.length()];
  29.      
  30.        /*
  31.         * To read content of the file in byte array, use
  32.         * int read(byte[] byteArray) method of java FileInputStream class.
  33.         *
  34.         */
  35.        fin.read(fileContent);
  36.      
  37.        //create string from byte array
  38.        String strFileContent = new String(fileContent);
  39.      
  40.        System.out.println("File content : ");
  41.        System.out.println(strFileContent);
  42.      
  43.     }
  44.     catch(FileNotFoundException e)
  45.     {
  46.       System.out.println("File not found" + e);
  47.     }
  48.     catch(IOException ioe)
  49.     {
  50.       System.out.println("Exception while reading the file " + ioe);
  51.     }
  52.   }
  53. }
  54.  
  55.  
  56. /*
  57. Output would be
  58. File content :
  59. This file is for demonstration of how to read file in byte array
  60. using Java FileInputStream.
  61. */