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 DemoStreamFile {
    private static long contaParoleConJ(Path percorso) throws IOException {
        try (Stream<String> righe = Files.lines(percorso, StandardCharsets.UTF_8)) {
            return righe.map(String::strip)
                    .filter(parola -> parola.startsWith("J"))
                    .count();
        }
    }

    public static void main(String[] args) throws IOException {
        Path cartella = Files.createTempDirectory("stream-file-");
        Path parole = cartella.resolve("parole.txt");
        Path vuoto = cartella.resolve("vuoto.txt");
        try {
            Files.writeString(parole, "Java\nReti\n JVM \n", StandardCharsets.UTF_8);
            Files.writeString(vuoto, "", StandardCharsets.UTF_8);
            System.out.println("Parole con J: " + contaParoleConJ(parole));
            System.out.println("File vuoto: " + contaParoleConJ(vuoto));
            try {
                contaParoleConJ(cartella.resolve("assente.txt"));
            } catch (NoSuchFileException errore) {
                System.out.println("File assente: " + errore.getClass().getSimpleName());
            }
        } finally {
            Files.deleteIfExists(parole);
            Files.deleteIfExists(vuoto);
            Files.deleteIfExists(cartella);
        }
    }
}
