Published by Patrick Mutisya · 14 days ago
Write Java code to perform file‑processing operations and handle any resulting exceptions safely.
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).
FileReader, BufferedReader, FileWriter, PrintWriter.FileInputStream, FileOutputStream, DataInputStream, DataOutputStream.close() (or using try‑with‑resources).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());
}
}
}
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());
}
}
}
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.
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());
}
}
}
IOException).NullPointerException).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)
}
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
}
}
}
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");
}
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());
}
}
}
IOException (and other checked exceptions) with try‑catch.finally for cleanup when not using try‑with‑resources.| Question | Key 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 |