Java Arena
Step 5 of 9

A file chosen by the user

A program is more useful when the user can pick the file. It then needs two Scanners: one for the keyboard and one for the file, each with a name of its own:

The file shopping.txt
apples
bread
coffee
import java.nio.file.Paths;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Which file?");
        String fileName = scanner.nextLine();

        try (Scanner fileScanner = new Scanner(Paths.get(fileName))) {
            while (fileScanner.hasNextLine()) {
                System.out.println(fileScanner.nextLine());
            }
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
Input
shopping.txt
Output
Which file?
apples
bread
coffee
  • scanner reads the keyboard, and fileScanner reads the file. Mixing them up is an easy slip: scanner.nextLine() inside the loop would read the keyboard, not the file.
  • Paths.get(fileName) takes any String, here the name the user typed.
  • A name that doesn't exist, such as shoping.txt, ends up in the catch block, and the program prints Error: shoping.txt.
  • The keyboard Scanner isn't put in a try (...). Closing it would close the keyboard input as well, and nothing more could be read from it.

Your task

Challenge 1 of 3

The program reads a file name and prints how many lines that file has. Fill in the blanks. For the input monday.txt and the files shown below, it prints:

Which file?
monday.txt: 3 lines

Challenge 2

Read a file name and then a line number. Print that line of the file: line 1 is the first one. If the file has fewer lines than that, print The file has only and its number of lines, followed by lines. The program prints no questions. For the input poem.txt and 2 and the files shown below, it prints:

the cat pretends to sleep

Challenge 3

Write a method countLines(String fileName) that returns how many lines the file has, or -1 if the file can't be read. The check runs System.out.println(countLines("draft.txt")); with the file shown below, and expects:

4