File handling is an important part of any application.Java has several methods for creating, reading, updating, and deleting files.

ยท         The File class from the java.io package, allows us to work with files.

 

A Java program to read the content from a text file and count the number of words in the file.

        
/*A program to read the content from a text file and count the number of words in the file*/

 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();

 

            }

            }

 

0 Comments