How to read the data from a file in Java?



The read(byte[] b) method of the FileInputStream class reads up to the b.length from this file input stream to the array of bytes. The method blocks until some input is available.

Example

import java.io.File;
import java.io.FileInputStream;
public class Sample {
   public static void main(String args[]) throws Exception {
      int count =0;
      File file = new File("myData");
      FileInputStream fis = new FileInputStream(file);
      byte[] bytesArray = new byte[(int)file.length()];
      fis.read(bytesArray);
      String s = new String(bytesArray);
      System.out.println("Contents of the given file are :: " +new String(bytesArray));
   }
}

Output

Contents of the given file are :: Hi how are you welcome to tutorialspoint

Advertisements