Java Program to Count Words in a File using java.util.Scanner Class

The following code counts the number of words and lines in a file. When you run the program, myFile.txt file is created  with 29 words and 3 lines. Scanner class is used to read the file. By Default, Scanner class uses whitespace  as delimiter to split the words. You can use useDelimiter to set any specified string as a delimiter.  useDelimiter(“\n“)  sets new line as delimiter. You can also use  nextLine() of Scanner class to read line in the file.

 

Running the Program

Output :

count words and lines in a file

 

Reference : Scanner Class in Java 

Leave a Reply