I/O

io6TryWithResourcesAndScanner

Path
pkg9io/io6TryWithResourcesAndScanner.java
Package
pkg9io
Study order
6
Run
Single-file source launch
Command
java pkg9io/io6TryWithResourcesAndScanner.java

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg9io/io6TryWithResourcesAndScanner.java
1package pkg9io;2 3import java.io.IOException;4import java.util.Scanner;5 6/*7 * io6TryWithResourcesAndScanner.java8 * ----------------------------------9 * Deterministic resource cleanup (try-with-resources) and parsing with Scanner.10 *11 * DEFINITION:12 *   try-with-resources auto-closes anything implementing AutoCloseable when the13 *   block exits (normally or via exception). Scanner tokenizes text/streams into14 *   typed values (ints, words, lines).15 *16 * KEY POINTS:17 *   - Resources close in REVERSE order of declaration, before catch/finally.18 *   - Exceptions during close are added as "suppressed" to the primary exception.19 *   - Implement AutoCloseable to make your own types usable in try-with-resources.20 *   - Scanner over a String is great for quick parsing without files.21 */22public class io6TryWithResourcesAndScanner {23 24    // Custom resource showing the auto-close hook25    static class Resource implements AutoCloseable {26        final String id;27        Resource(String id) { this.id = id; System.out.println("  open  " + id); }28        void use()          { System.out.println("  use   " + id); }29        @Override public void close() { System.out.println("  close " + id); }30    }31 32    public static void main(String[] args) throws IOException {33        System.out.println("Resources close in reverse order:");34        try (Resource a = new Resource("A");35             Resource b = new Resource("B")) {     // B closes before A36            a.use();37            b.use();38        }39 40        // Scanner: parse mixed tokens from a String41        System.out.println("\nScanner parsing tokens:");42        try (Scanner sc = new Scanner("Ada 36 3.14 true")) {43            System.out.println("  word   = " + sc.next());44            System.out.println("  int    = " + sc.nextInt());45            System.out.println("  double = " + sc.nextDouble());46            System.out.println("  bool   = " + sc.nextBoolean());47        }48 49        // Scanner reading lines, with a custom delimiter50        System.out.println("\nCSV via delimiter:");51        try (Scanner sc = new Scanner("red,green,blue").useDelimiter(",")) {52            while (sc.hasNext()) System.out.println("  color = " + sc.next());53        }54        // Note: reading interactive input would be: new Scanner(System.in)55    }56}