This is the first solution to count number of lines, words and characters in a given file. This approach uses the FileReader, BufferedReader, StringTokenizer and String methods.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
public class LinesWordsCharacters {
static int cntLines,cntWords,cntChars;
public static void main(String[] args) throws IOException {
String lineRead;
/* Display the current sampleFile.txt file contents */
displayFileContent("C:\\Users\\Nagendra\\sampleFile.txt","old");
/* Re-open the same sampleFile.txt file using BufferedReader and
FileReader, to search for a given word in each line of this file */
FileReader fileRead=new FileReader("C:\\Users\\Nagendra\\sampleFile.txt");
@SuppressWarnings("resource")
BufferedReader fileToRead = new BufferedReader(fileRead);
System.out.println();
/* Read line by line and keep track the counter for lines,
* Call the function parseEachLine()
* keep track the counter for words in each line, and
* keep track the counter for characters in each line*/
System.out.println("Number of Lines-Number of Words-Number of Characters");
while ((lineRead= fileToRead.readLine()) != null) {
cntLines++;
StringTokenizer strTokens=new StringTokenizer(lineRead);
cntWords+=strTokens.countTokens();
cntChars+=lineRead.length();
}
System.out.print(cntLines+" "+cntWords+" "+cntChars);
}
private static void displayFileContent(String filePath, String neworold) throws IOException {
/* Display the sample file contents to the console using the
BufferedReader and FileReader */
FileReader fRead=new FileReader(filePath);
@SuppressWarnings("resource")
BufferedReader fileToRd = new BufferedReader(fRead);
String lineRead;
System.out.println("The contents of the "+neworold+" file are below");
System.out.println("----------------------------------");
while ((lineRead= fileToRd.readLine()) != null)
System.out.println(lineRead);
fileToRd.close();
}
}
OUTPUT:
The contents of the old file are below
----------------------------------
This is the reason why I like Java language.
Sky is the limit for Java language features.
Hence Java language is in my learning list.
Many people are liking Java language since two decades.
Number of Lines-Number of Words-Number of Characters
4 34 188

Leave a comment