CS101 · Annotated SlidesChapter 12 — Exception Handling and Text I/O
Chapter 12 · Annotated slides

Exception Handling and Text I/O

The File class, writing text with PrintWriter, try-with-resources that closes files automatically, and reading text with Scanner.

Slide text Study notes Highlight: key words Tips, tricks & traps Seen again elsewhere How it can come up

Exception Handling and Text I/O

CS101 · Chapter 12
1
Slide 2: Objectives
Exam weight Low
  1. Objectives: File class, PrintWriter, Scanner, try-with-resources.
Slide 3: The File Class
Exam weight High
  1. File represents a file or directory path; it does NOT read or write contents.
🎯 How this can come up · 1 question
True / False

The File class is used to read the contents of a file.

Slide 4: Obtaining file properties and manipulating file
Exam weight Low
  1. File methods: exists(), length(), canRead(), isDirectory(), getName(), delete().
Slide 5: Problem: Explore File Properties
Exam weight Low
  1. Explore file properties.
Slide 6: Example to Explore File Properties
Exam weight Low
  1. Example code.
Slide 7: Text I/O
Exam weight Low
  1. Text I/O: PrintWriter writes, Scanner reads.
Slide 8: Writing Data Using PrintWriter
Exam weight High
  1. PrintWriter output = new PrintWriter(file); print/println/printf; close() at the end.
🎯 How this can come up · 1 question
MCQ

Which class writes text data to a file?

Slide 9: Example Writing Data Using PrintWriter
Exam weight Low
  1. Example writing data.
Slide 10: Try-with-resources
Exam weight High
  1. try (PrintWriter out = new PrintWriter(file)) { … } closes the file automatically.
🎯 How this can come up · 1 question
MCQ

try-with-resources is used to:

Slide 11: Example Writing Data Using PrintWriter with try automatically closes the file
Exam weight Low
  1. Example with try-with-resources.
Slide 12: Reading Data Using Scanner
Exam weight High
  1. Scanner input = new Scanner(new File("scores.txt")); while (input.hasNext()) …
Exam trapnew Scanner("scores.txt") reads the STRING, not the file. Wrap it in new File(...).
Slide 13: Example Reading Data from file Using Scanner and display on Output Screen
Exam weight Low
  1. Example: read from a file and display.
Slide 14: Slide 14
Exam weight Low
  1. Example code.
Slide 15: Slide 15
Exam weight Low
  1. Example output.