Skip to content

Instantly share code, notes, and snippets.

@kunals201
Created January 31, 2018 05:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kunals201/992f6262ef02f376aa15b4b26bef0314 to your computer and use it in GitHub Desktop.
Save kunals201/992f6262ef02f376aa15b4b26bef0314 to your computer and use it in GitHub Desktop.
This program count the number of words
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class WordCount {
public static void main(String[] args) throws FileNotFoundException {
countWords("sample.txt");
}
/**
* this method count number of words from the text file and finally print the number of words * * @param fileName
*/
public static void countWords(String fileName) {
try {
long wordCount = Files.lines(Paths.get(fileName))
.flatMap(str -> Stream.of(str.split("[ ,.!?\r\n]"))).count();
System.out.println("Number of words in file : " + wordCount);
} catch (FileNotFoundException fnf) {
System.out.println("Exception Occurred" + fnf.getMessage());
} catch (IOException io) {
System.out.println("Exception Occurred" + io.getMessage());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment