Pages

Program to count number of lines and words in a file in Java

This simple count the number of lines and words in a file. In this program we use FileReader and BufferedReader class defined in java.io package to read the content of file. StringTokenizer class defined in java.util package is used to count no of words in the file.

CountLineWord.java
import java.io.FileReader;
import java.io.BufferedReader;
import java.util.StringTokenizer;

class CountLineWord{
public static void main(String[] args){

FileReader fileRead;
BufferedReader buffRead;
String line="", content = "";
int nline = 0, nword = 0;
try{
   //retrive content of file
fileRead = new FileReader("hello.txt");
buffRead= new BufferedReader(fileRead);
    //read line in a file
while((line = buffRead.readLine()) != null){
content += line + ""; //store content
nline++; //no of line count
}

StringTokenizer token = new StringTokenizer(content);
while(token.hasMoreTokens()){
token.nextToken();
nword++; //count no of words
}

System.out.println("File Content : " + content);
System.out.println("Number of Lines in the file : " + nline);
System.out.println("Number of Words in the file : " + nword);


}
catch (IOException ex){
System.out.println(ex);
}
}
}

@msucil

Phasellus facilisis convallis metus, ut imperdiet augue auctor nec. Duis at velit id augue lobortis porta. Sed varius, enim accumsan aliquam tincidunt, tortor urna vulputate quam, eget finibus urna est in augue.

No comments:

Post a Comment