public class TryWithResources
1: import java.util.Scanner;
2: import java.util.ArrayList;
3: import java.io.File;
4: import java.io.FileNotFoundException;
6: public class TryWithResources {
8: public static void main(String[] args) {
9: Scanner kbd = new Scanner(System.in);
10: ArrayList<String> words = new ArrayList<String>();
11: String name;
12: String word;
14: System.out.print("Enter the name of the file: ");
15: name = kbd.nextLine();
16: try (Scanner fin = new Scanner(new File(name))) {
17: while (fin.hasNext()) {
18: words.add(fin.next());
19: }
20: fin.close(); // not NECESSARY, but still a good idea
22: System.out.println("\n" + name + " has " + words.size()
23: + " words in it.\n"
24: + "The first is " + words.get(0)
25: + " and the last is " + words.get(words.size() - 1) + "\n");
26: System.out.println("The middle word is "
27: + words.get(words.size() / 2) + ".\n");
28: } catch (FileNotFoundException fnf) {
29: System.out.println("Sorry -- couldn't open that file!");
30: }
31: }
33: }