Write a text to a temporary file, then read it back with a BufferedReader and print the number of lines, words and characters (like the Unix wc command).
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class Main {
public static void main(String[] args) throws IOException {
Path f = Files.createTempFile("essay", ".txt");
Files.writeString(f, "Java makes file handling simple.\nUse NIO for new code.\n\nAlways close your streams!\n");
int lines = 0, words = 0, chars = 0;
try (BufferedReader r = Files.newBufferedReader(f)) {
String line;
while ((line = r.readLine()) != null) {
lines++;
chars += line.length();
if (!line.isBlank()) words += line.trim().split("\\s+").length;
}
}
System.out.println(lines + " lines, " + words + " words, " + chars + " chars (" + Files.size(f) + " bytes on disk)");
Files.delete(f);
}
}
4 lines, 14 words, 79 chars (83 bytes on disk)
readLine strips line terminators, which is why the byte count is 4 higher than the character count.