How to count the number of lines in a text file using Java?

To count the number of lines in a file

  • Instantiate the FileInputStream class by passing an object of the required file as parameter to its constructor.
  • Read the contents of the file to a bytearray using the read() method of FileInputStream class.
  • Instantiate a String class by passing the byte array obtained, as a parameter its constructor.
  • Now, split the above string into an array of strings using the split() method by passing the regular expression of the new line as a parameter to this method.
  • Now, find the length of the obtained array.


public class NumberOfCharacters {
   public static void main(String args[]) throws Exception{
      File file = new File("data");
      FileInputStream fis = new FileInputStream(file);
      byte[] byteArray = new byte[(int)file.length()];;
      String data = new String(byteArray);
      String[] stringArray = data.split("\r
");       System.out.println("Number of lines in the file are ::"+stringArray.length);    } }



Number of lines in the file are ::3