Post

Created by @nathanedwards
 at November 1st 2023, 4:26:28 pm.

AP Computer Science Exam Question

Consider the following code snippet:

import java.io.*;

public class FileExample {

    public static void main(String[] args) {
        try {
            File file = new File("sample.txt");
            FileWriter writer = new FileWriter(file);
            writer.write("Hello, World!");
            writer.close();
            
            file = new File("sample.txt");
            FileReader reader = new FileReader(file);
    
            int character;
            while ((character = reader.read()) != -1) {
                System.out.print((char) character);
            }
            reader.close();
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

Explain the purpose of the above code, step-by-step, and describe how it interacts with files.

Answer

The given code demonstrates the usage of file classes in Java to write content to a file and then read its content.

  1. First, the code imports the necessary classes from the java.io package, which includes the File, FileWriter, and FileReader.

  2. Inside the main method, a new File object, file, is created with the filename "sample.txt". This represents the file in which we will be writing the content.

  3. The code then creates a FileWriter object, writer, using the file object. This allows us to write data to the file.

  4. The write method of the writer object is called with the string "Hello, World!" as its argument. This writes the specified content to the file.

  5. After writing the content, the writer is closed using the close method. This is an important step to ensure that any resources associated with the writer are released.

  6. Next, a new File object, file, is created with the same filename "sample.txt". This represents the file from which we will be reading the content.

  7. A FileReader object, reader, is created using the file object. This allows us to read data from the file.

  8. Inside a while loop, the read method of the reader object is called. This reads the characters from the file one by one. The loop continues until the read method returns -1, indicating the end of the file.

  9. If a character is read, it is casted to a char type and printed to the console using System.out.print. This displays the content of the file.

  10. Finally, the reader is closed using the close method.

The purpose of the code is to demonstrate the process of writing content to a file and then reading its content. It shows how to use the File, FileWriter, and FileReader classes from the java.io package to interact with files in Java.