B2.5 Visualising File Operations - Worksheet - Java
Name: __________________________________________________________________ Date: _____________________
Part 1: The Mental Model
In Java, when you use a Scanner (for reading) or FileWriter (for writing) imagine an invisible "cursor" moving through the file.
The Golden Rule: You generally cannot read what is behind the cursor without closing and re-opening the file (or using more complex classes like RandomAccessFile).
Part 2: The "Ghost File" Scenario
Analyse the following Java code snippet. It runs without errors, but the variable data ends up empty.
import java.io.*;
import java.util.Scanner;
public class GhostFile {
public static void main(String[] args) {
try {
// Step 1: Write data
FileWriter writer = new FileWriter("my_data.txt");
writer.write("Hello World");
// writer.flush(); // Ensure data is written
// Step 2: Try to read data immediately
File file = new File("my_data.txt");
Scanner reader = new Scanner(file);
String data = "";
if (reader.hasNextLine()) {
data = reader.nextLine();
}
System.out.println("Data found: " + data);
writer.close();
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Task 1: The Logic Error. Even though we created a Scanner to read the file, why might it fail to read the "Hello World" text we just wrote? (Hint: Think about buffers and whether the file has been saved/closed yet).
_____________________________________________________________________________________________________
_____________________________________________________________________________________________________
Part 3: Fixing the Bug
There is a specific order of operations required to ensure the data is safely saved before attempting to read it. Write the corrected sequence of code below.
The Correct Sequence:
Write the data.
- _____________________________________________________________ (Critical Step!)
- Open the Scanner to read.
// Write the corrected code snippet here:
FileWriter writer = new FileWriter("my_data.txt");
writer.write("Hello World");
__________________________________ // Missing line
Scanner reader = new Scanner(new File("my_data.txt"));
// ... read data ...
Part 4: Challenge - The "Append" Trap
A student wants to add a new score to a list of high scores. They run this code:
FileWriter writer = new FileWriter("scores.txt"); // Danger!
writer.write("Player1: 500");
writer.close();
What happens to the old scores that were already in the file?
[ ] They are moved to the bottom.
[ ] They are kept safely at the top.
[ ] They are completely deleted.
How should the first line be modified to correct this issue?
____________________________________________________________________________________________________