Q:

Java Program to find the number of the words in the given text file

belongs to collection: Java String Programs

0

In this program, we need to find the most repeated word present in given text file. This can be done by opening a file in read mode using file pointer. Read the file line by line. Split a line at a time and store in an array. Iterate through the array and count the word. The content of data.txt file used in the program is shown below.

data.txt

A computer program is a collection of instructions that performs specific task when executed by a computer.

Computer requires programs to function.

Computer program is usually written by a computer programmer in programming language.

A collection of computer programs, libraries, and related data are referred to as software.

Computer programs may be categorized along functional lines, such as application software and system software.

Algorithm

  • STEP 1: START
  • STEP 2: DEFINE String line
  • STEP 3: SET count =0
  • STEP 4: USE File Reader to open file in read mode.
  • STEP 5: READ line from file
  • STEP 6: REPEAT STEP 7 to STEP 8 UNTIL reach the end of file
  • STEP 7: SPLIT lines into words and STORE in array string words[].
  • STEP 8: count = count + words.length
  • STEP 9: PRINT count.
  • STEP 10: END

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program:

import java.io.BufferedReader;  
import java.io.FileReader;  
  
public class CountWordFile  
{  
    public static void main(String[] args) throws Exception {  
        String line;  
        int count = 0;  
  
        //Opens a file in read mode  
        FileReader file = new FileReader("data.txt ");  
        BufferedReader br = new BufferedReader(file);  
  
        //Gets each line till end of file is reached  
        while((line = br.readLine()) != null) {  
            //Splits each line into words  
            String words[] = line.split("");  
            //Counts each word  
            count = count + words.length;  
  
        }  
  
        System.out.println("Number of words present in given file: " + count);  
        br.close();  
    }  
}  

Output:

Number of words present in given file: 63

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java Program to separate the Individual Characters... >>
<< Java Program to find the most repeated word in a t...