import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.stream.Stream;

public class FileStreamDemo {
    private static long countWordsWithJ(Path path) throws IOException {
        try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) {
            return lines.map(String::strip)
                    .filter(word -> word.startsWith("J"))
                    .count();
        }
    }

    public static void main(String[] args) throws IOException {
        Path folder = Files.createTempDirectory("stream-file-");
        Path words = folder.resolve("words.txt");
        Path empty = folder.resolve("empty.txt");
        try {
            Files.writeString(words, "Java\nNets\n JVM \n", StandardCharsets.UTF_8);
            Files.writeString(empty, "", StandardCharsets.UTF_8);
            System.out.println("Words with J: " + countWordsWithJ(words));
            System.out.println("Empty file: " + countWordsWithJ(empty));
            try {
                countWordsWithJ(folder.resolve("absent.txt"));
            } catch (NoSuchFileException error) {
                System.out.println("Absent file: " + error.getClass().getSimpleName());
            }
        } finally {
            Files.deleteIfExists(words);
            Files.deleteIfExists(empty);
            Files.deleteIfExists(folder);
        }
    }
}
