This tutorial explains how to count number of words in a file in java. Find Number of words should be a valuable part. Reason for Counting word occurrence in because almost all the text boxes that rely on user input have a certain limit on the number of characters that can be inserted.
sample.txt
we are going to use below text file content using java code.
FileWordCount.java
Output:-
-----------------
This is all about Java Program to Count Number of Words in a File. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.
Count Number of Words in a File In Java :
Lets see the Following Java program is the total number of words in a file.sample.txt
we are going to use below text file content using java code.
FileWordCount.java
package demo; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; public class FileWordCount { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub File f1=new File("sample.txt"); //Creation of File Descriptor for input file String[] words=null; //Intialize the word Array int wc=0; //Intialize word count to zero FileReader fr = new FileReader(f1); //Creation of File Reader object BufferedReader br = new BufferedReader(fr); //Creation of BufferedReader object String s; while((s=br.readLine())!=null) //Reading Content from the file { words=s.split(" "); //Split the word using space wc=wc+words.length; //increase the word count for each word } fr.close(); System.out.println("Number of words in the file:- " +wc); //Print the word count } }
Output:-
-----------------
This is all about Java Program to Count Number of Words in a File. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.
// If you use java8, this is a more succinct way using streams:
ReplyDeleteint wordCount = Files.lines(Paths.get("sample.txt"))
.mapToInt(s -> s.split("\\s").length)
.sum()
// Note that splitting on \s will split on any whitespace character
Thanks for the great information...
Delete