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:
apples
bread
coffeeimport 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());
}
}
}
shopping.txtWhich file?
apples
bread
coffeescannerreads the keyboard, andfileScannerreads 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 thecatchblock, and the program printsError: 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.