diff --git a/src/com/codecafe/java8/streams/usecases/ReadFromFile.java b/src/com/codecafe/java8/streams/usecases/ReadFromFile.java index 547bb68..0d78fd5 100644 --- a/src/com/codecafe/java8/streams/usecases/ReadFromFile.java +++ b/src/com/codecafe/java8/streams/usecases/ReadFromFile.java @@ -3,16 +3,22 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; +import java.util.stream.Stream; // Read a file and count the occurrence of a word in it public class ReadFromFile { public static void main(String[] args) throws IOException { - String path = "C:\\Users\\Abhinav\\git\\java-8\\src\\com\\codecafe\\java8\\streams\\usecases\\hosts"; + String path = "src/com/codecafe/java8/streams/usecases/hosts"; String searchWord = "localhost"; - System.out.printf("occurrence of word [%s] = %d", searchWord, Files.lines(Paths.get(path)) - .filter(line -> line.contains(searchWord)) - .count()); + long count = 0; + + try (Stream lines = Files.lines(Paths.get(path))) { + count = lines.filter(line -> line.contains(searchWord)) + .count(); + } + + System.out.printf("occurrence of word [%s] = %d", searchWord, count); } -} +} \ No newline at end of file