← Java from Scratch Lesson 58 of 88 · 10 XP

Reading files

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

import java.io.File;
import java.util.Scanner;

try (Scanner sc = new Scanner(new File("scores.txt"))) {     // FileNotFoundException — checked
    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        …
    }
}

With Files:

String all = Files.readString(Path.of("a.txt"));
List<String> lines = Files.readAllLines(Path.of("a.txt"));
try (Stream<String> s = Files.lines(Path.of("big.txt"))) { … }   // lazily — for big files

Reading everything into memory (readAllLines) is for small files; big ones are read line by line.

Task. The program has already written the name score lines from the input to scores.txt. Read the file (with Scanner(new File(...))) and print the best player as name (score), the total score and the number of players.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.