Overview

In this reading we’ll be introduced to the basics of reading from and writing to files. We’ll also learn about Java’s mechanisms for allowing us to deal with exceptional events, such as trying to open a file that doesn’t exist.

Required Reading

Sections 12.3, excluding 12.3.3 and 12.3.6, (pp. 394-399, 404-407) from the course textbook.

Learning Objectives

BASIC Learning Objectives

Each student will be responsible for learning and demonstrating proficiency in the following objectives PRIOR to the class meeting. The reading quiz will test these objectives.

  1. Describe the structure by which files and directories are organized on a computer.
  2. Explain the role of the BufferedReader and BufferedWriter classes in performing file reads and writes.
  3. Compare and contrast checked and unchecked exceptions.
  4. Describe the roles of the try, catch, and finally blocks when dealing with exceptions.
  5. Given a BufferedReader object, write a Java statement that prints out the next line in a file.
  6. Given a BufferedWriter object, write a Java statement that writes text to a file.

ADVANCED Learning Objectives

The following objectives should be mastered by each student DURING and FOLLOWING the class session through active work and practice.

  1. Generate a call stack while tracing through Java code.
  2. Write, read, and trace code that uses try, catch, and finally blocks to handle exceptions.
  3. Write, read, and trace code that reads from and writes to one or more files.

Pre-class Exercises

These exercises are geared towards mastering the BASIC learning objectives listed above. You are expected to submit them before class and it is highly recommended that you complete them before attempting the reading quiz.

  1. Draw a tree that represents some of the files/folders in your Desktop folder and at least one of the folders on your desktop. If you keep a “clean” desktop, just make something up that is reasonable.

  2. What is the relationship between the FileReader and the BufferedReader when it comes to reading a file?

  3. Assume that you have the following BufferedReader object.

    String filename = FileChooser.pickAFile():
    BufferedReader br = new BufferedReader(new FileReader(filename));

    Write a loop that prints out the first 10 lines of this file. You may assume that there are at least 10 lines in the file.

  4. Assume that you have the following BufferedReader object.

    String filename = FileChooser.pickAFile():
    BufferedWriter bw = new BufferedWriter(new FileWriter(filename));

    Write a loop that writes the numbers 5 to 10 to the chosen file, with each number on its own line.