Created
January 31, 2018 05:40
-
-
Save kunals201/6d6ed0cae0ce437ee4d1761d71104647 to your computer and use it in GitHub Desktop.
Number of Words count
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 IOException { | |
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) throws IOException { | |
Stream<String> stream = Files.lines(Paths.get(fileName)); | |
try (stream) { | |
long wordCount = stream.flatMap(str -> Stream.of(str.split("[ ,.!?\r\n]"))) | |
.count(); | |
System.out.println("Number of words in file : " + wordCount); | |
} catch (Exception e) { | |
System.out.println("Exception Occurred" + e.getMessage()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment