Program to find number lines and words in a given file



import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.StringTokenizer;

public class LineWordCount {

public void calculate(String fileName) throws FileNotFoundException {
long lineCount = 0;
long wordCount = 0;
Scanner scanner = null;
try {
scanner = new Scanner(new FileInputStream(fileName));
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lineCount++;
wordCount += new StringTokenizer(line, " ").countTokens();
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (scanner != null) {
scanner.close();
}

}
System.out.println(lineCount + "," + wordCount);
}

public static void main(String[] args) throws FileNotFoundException {
String fileName = "filepath/file.txt";
new LineWordCount().calculate(fileName);
}
}


Comments

Popular posts from this blog

Java important topics list for interviews

Tough Sql practise questions for interviews involving SELECT queries - Part 2

DBMS important topics list for interviews

Tough Sql practise questions for interviews involving SELECT queries - Part 1

Producer Consumer Problem with Blocking Queue in Java.

Animation for String search - KMP Algorithm

Interactive Data Structure visualizations/animations for algorithms

Replace Occurances of the given string