Write code to perform file-processing operations

Published by Patrick Mutisya · 14 days ago

Cambridge A-Level Computer Science 9618 – Topic 20.2 File Processing and Exception Handling

20.2 File Processing and Exception Handling

Learning Objective

Write Java code to perform file‑processing operations and handle any resulting exceptions safely.

1. Why Use Files?

Files allow programs to store data permanently, share information between runs, and communicate with other applications. In A‑Level, the focus is on text files (character streams) and binary files (byte streams).

2. Basic File‑Processing Concepts

  • Stream: A sequence of data elements made available over time.
  • Character stream classes: FileReader, BufferedReader, FileWriter, PrintWriter.
  • Byte stream classes: FileInputStream, FileOutputStream, DataInputStream, DataOutputStream.
  • Opening a file: Creating an appropriate stream object.
  • Closing a file: Releasing system resources with close() (or using try‑with‑resources).

3. Opening, Reading and Writing Text Files

3.1 Reading a Text File

import java.io.*;

public class ReadFileExample {

public static void main(String[] args) {

try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {

String line;

while ((line = br.readLine()) != null) {

System.out.println(line);

}

} catch (IOException e) {

System.err.println("Error reading file: " + e.getMessage());

}

}

}

3.2 Writing to a Text File

import java.io.*;

public class WriteFileExample {

public static void main(String[] args) {

try (PrintWriter pw = new PrintWriter(new FileWriter("output.txt"))) {

pw.println("First line");

pw.println("Second line");

} catch (IOException e) {

System.err.println("Error writing file: " + e.getMessage());

}

}

}

3.3 Using Try‑with‑Resources

When a stream is declared inside the parentheses of a try statement, it is automatically closed at the end of the block, even if an exception occurs.

4. Binary File Processing

Binary files store data in raw byte form. Java’s DataInputStream and DataOutputStream simplify reading and writing primitive types.

import java.io.*;

public class BinaryFileExample {

public static void main(String[] args) {

try (DataOutputStream dos = new DataOutputStream(new FileOutputStream("numbers.bin"))) {

dos.writeInt(42);

dos.writeDouble(3.14159);

} catch (IOException e) {

System.err.println("Write error: " + e.getMessage());

}

try (DataInputStream dis = new DataInputStream(new FileInputStream("numbers.bin"))) {

int i = dis.readInt();

double d = dis.readDouble();

System.out.println("Read values: " + i + ", " + d);

} catch (IOException e) {

System.err.println("Read error: " + e.getMessage());

}

}

}

5. Exception Handling Basics

  • Exception: An event that disrupts the normal flow of a program.
  • Checked exceptions: Must be declared or caught (e.g., IOException).
  • Unchecked exceptions: Runtime exceptions (e.g., NullPointerException).

6. The Try‑Catch‑Finally Construct

try {

// code that may throw an exception

} catch (SpecificException e) {

// handle that specific exception

} catch (Exception e) {

// handle any other exception

} finally {

// code that always runs (e.g., close resources)

}

6.1 Example with Explicit Close

BufferedReader br = null;

try {

br = new BufferedReader(new FileReader("data.txt"));

// read data …

} catch (FileNotFoundException e) {

System.err.println("File not found");

} catch (IOException e) {

System.err.println("I/O error");

} finally {

if (br != null) {

try {

br.close();

} catch (IOException e) {

// ignore secondary exception

}

}

}

7. Creating Custom Exceptions

Custom exceptions let you signal domain‑specific error conditions.

public class InvalidRecordException extends Exception {

public InvalidRecordException(String message) {

super(message);

}

}

Usage:

if (!record.is \cdot alid()) {

throw new InvalidRecordException("Record format is invalid");

}

8. Full Example – Processing a CS \cdot File with Error Handling

import java.io.*;

public class CS \cdot Processor {

public static void main(String[] args) {

String inputFile = "students.csv";

String outputFile = "valid_students.txt";

try (BufferedReader br = new BufferedReader(new FileReader(inputFile));

PrintWriter pw = new PrintWriter(new FileWriter(outputFile))) {

String line;

int lineNum = 0;

while ((line = br.readLine()) != null) {

lineNum++;

try {

String[] fields = line.split(",");

if (fields.length != 3) {

throw new InvalidRecordException("Incorrect number of fields");

}

String name = fields[0].trim();

int age = Integer.parseInt(fields[1].trim());

double gpa = Double.parseDouble(fields[2].trim());

if (age < 0 || gpa < 0.0) {

throw new InvalidRecordException("Negative values not allowed");

}

pw.printf("%s,%d,%.2f%n", name, age, gpa);

} catch (InvalidRecordException | NumberFormatException e) {

System.err.println("Line " + lineNum + " skipped: " + e.getMessage());

}

}

} catch (IOException e) {

System.err.println("File error: " + e.getMessage());

}

}

}

9. Summary Checklist

  • Know the difference between character and byte streams.
  • Always close streams – use try‑with‑resources where possible.
  • Handle IOException (and other checked exceptions) with try‑catch.
  • Use finally for cleanup when not using try‑with‑resources.
  • Define custom exception classes to represent specific error conditions.

10. Practice Questions

QuestionKey Concepts Tested
Write a method that reads a text file and returns the number of lines that contain the word “error”. Include appropriate exception handling.BufferedReader, readLine(), contains(), try‑catch
Explain the difference between a checked and an unchecked exception, giving one example of each.Theory – exception hierarchy
Modify the CS \cdot processor example so that it creates a log file listing all skipped lines and the reason for skipping.FileWriter, multiple PrintWriter objects, custom exception messages
Demonstrate how to use DataOutputStream to write an array of integers to a binary file, then read them back using DataInputStream.Binary streams, loops, exception handling

Suggested diagram: Flow of file processing – open → read/write → handle exceptions → close (or auto‑close with try‑with‑resources).