Sunday, August 11, 2019

Java Program to Count Number of Words in a File

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.

Java Program to Count Number of Words in a File


 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.
Simple Form Validation In Reactjs Example
Create a Dropdown Menu using ReactJS
Installing React Native on Windows Tutorial
Create Dropdown Menu In React Native
How To Customize Button In React Native
Facebook loading animation using CSS3
Facebook Style Chat Application with jQuery and CSS
Append Or Prepend HTML Using ReactJS
Create Ripple Animation Effect Using Css
Ripple Effect Animation On Button Click With CSS3

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:-
-----------------
Java Program to Count Number of Words in a File


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.

2 comments:

  1. // If you use java8, this is a more succinct way using streams:
    int 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

    ReplyDelete