File Metadata Determiner

We will see how java IO package can be used to read total number of characters, words and lines from a file


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import static java.lang.IO.println;

/**
 * @author Konstantine Vashalomidze
 */
public class ReadFileAndCountTotalNumbers {
    static void main() {
        // We use buffered reader mainly because it has convenient method to read lines
        // This program assumes that there is a file called 'somesiski' at the project root level
        try (var reader = new BufferedReader(new FileReader("somesiski"))) { 
            int countChars = 0;
            int countLines = 0;
            int countWords = 0;
            String line = reader.readLine();
            while (line != null) {
                // count number of chars in a line
                countChars += line.length();
                // count line
                countLines++;
                // count words
                String[] split = line.split(" ");
                for (var s : split) {
                    if (!s.isEmpty()) {
                        countWords++;
                    }
                }
                // process next line 
                line = reader.readLine();
                // repeat until no next lines to process
            }
            // display the result
            println("Chars: " + countChars + " Lines: " + countLines + " Words: " + countWords);
        } catch (IOException e) {
            println(e.getMessage());
            throw new RuntimeException(e);
        }
    }
}

And this was all, now you can simply run:

java ReadFileAndCountTotalNumbers.java
and it will display the results.