import java.nio.file.Path; import java.nio.file.Files; import java.io.BufferedReader; import java.io.IOException; import java.nio.file.NoSuchFileException; public class WC { public static void main(String[] args) { Path p = Path.of(args[0]); //try with resources closes the file for you try(BufferedReader br = Files.newBufferedReader(p);) { String line = ""; int words = 0; int lines = 0; int chars = 0; while( (line = br.readLine()) != null) { //System.out.println(line); lines++; chars += 1 + line.length(); words += line.split("\\s+").length; } System.out.printf("chars: %s\n", chars); System.out.printf("lines: %s\n", lines); System.out.printf("words: %s\n", words); } catch(NoSuchFileException ex) { System.err.printf("File %s not found.\n", p); } catch(IOException ex) { ex.printStackTrace(); } } }