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
Post a Comment