Read a file and count its lines and words

Description: Write a file poem.txt with three lines. Read it back and print the number of lines and the number of words.

Hint:

  • Use Files.write and Files.readAllLines. Count the words with split("\\s+").

Solution

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

public class Main {
    public static void main(String[] args) throws IOException {
        Path file = Path.of("poem.txt");
        Files.write(file, List.of("Roses are red", "Violets are blue", "Java is fun"));

        List<String> lines = Files.readAllLines(file);
        int words = 0;
        for (String line : lines) {
            words += line.trim().split("\\s+").length;
        }
        System.out.println("Lines: " + lines.size());
        System.out.println("Words: " + words);
    }
}
Output

Lines: 3
Words: 9

How it works

  • readAllLines gives a list with one item for each line.
  • \\s+ is a regular expression for one or more spaces.

Read Java File Handling.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.