Code Companion
Java

Programming technique · B2.5.1

File processing

A text file provides persistent data: its contents can remain after the program ends. Sequential file processing reads or writes the file in order, so the program must choose the correct mode and close the resource reliably.

IB DP CS standard B2.5.1: Construct code to manipulate text files by opening a sequential file in read, write and append modes, reading/writing/appending data and closing the file when operations are complete.

Persistent

Unlike an ordinary variable or list, file contents can still exist after the program has stopped.

Text file

The stored data is text. Numbers must be represented as text in the file and converted when numeric processing is required.

Sequential

The core model processes lines in order rather than jumping directly to an arbitrary record position.

The same file can be opened for different purposes
flowchart TD A[Program] --> B[Open sequential text file] B --> C{Which operation?} C -- Read --> D[Process existing lines in sequence] C -- Write --> E[Replace existing file contents] C -- Append --> F[Add new content at the end] D --> G[Close reliably] E --> G F --> G B -. unavailable .-> H[Handle the failure and explain the problem]

Choose read, write or append deliberately, then use a resource-management structure so the file closes reliably.

Mode choice changes the file

OperationExisting fileMissing fileEffect
ReadUses the existing contentsFails: there is nothing to readDoes not alter the file
WriteReplaces/truncates the existing contentsCreates a new file where permittedStarts new contents
AppendPreserves existing contentsCreates a new file where permittedAdds at the end
Java syntax: new FileWriter(path) is write/replace mode; new FileWriter(path, true) is append mode. Reading with Scanner(new File(path)) does not create a missing file.
Python syntax: open(path, "w") is write/replace mode, open(path, "a") appends and open(path, "r") reads. Reading a missing file raises FileNotFoundError.

Write a text file

Opening a FileWriter without append mode replaces the existing contents. Try-with-resources closes the writer automatically when the block ends.

Opening with mode "w" creates or replaces the file. A with block closes it automatically when the block ends.

Append instead of overwrite

Pass true to the FileWriter constructor to add new content at the end. Include a line separator when each record should occupy its own line.

Use mode "a" to add new content at the end without replacing existing records. Include \n when each record should occupy its own line.

Read line by line

Sequential reading normally checks whether another line exists, reads that line, processes it, then moves to the next one.

Trace the file state, not only the variables

StepOperationnotes.txt after the step
Startexisting fileOld note
1write First noteFirst note — old contents replaced
2append Second noteFirst note
Second note
3read line by lineunchanged

Missing and empty are different

Missing file

The requested path does not identify a readable file. Reading should fail safely with a useful message.

Empty file

The file exists but contains no usable lines. This is not the same as the resource being unavailable.

Reliable closure

Java try-with-resources and Python with close the resource automatically, including when an error interrupts normal processing.

Check your understanding

Answer each question before opening the model answer.

  1. A file already contains 30 records. What happens if you open it in write/replace mode and write one new record?

    Reveal model answer

    The previous contents are replaced/truncated; the file finishes with the new written contents, not the original 30 records.

  2. Which mode should you use when a new log entry must be added without deleting earlier entries?

    Reveal model answer

    Append mode: FileWriter(path, true) in the Java model or open(path, "a") in Python.

  3. What is the difference between a missing file and an empty file?

    Reveal model answer

    A missing file is unavailable at the requested path. An empty file exists but contains no usable records.

  4. Why do these examples not call close() manually?

    Reveal model answer

    Try-with-resources in Java and with in Python manage the resource lifetime and close it automatically when the block exits.

Use a clear record format

Choose a delimiter or line structure that your reading code can interpret consistently.

Keep paths simple

During development, place small data files in a predictable project folder and report the path when debugging.

Stay within the file standard

This page teaches sequential text files. Databases, binary serialization and OOP persistence are separate topics.

Challenges Choose one

Choose a challenge that feels appropriate for you. Code heat is only a rough estimate, not a fixed level.

Quote of the Day

Challenge ID: PC-T17-C01 · Standards: B2.5.1

Create a text file containing one quotation. Write a program that opens the file, reads the quotation and outputs it with a clear heading. Handle a missing file without crashing.

A document and computer screen representing a quotation read from a file.

Random Quote

Challenge ID: PC-T17-C02 · Standards: B2.2.2, B2.5.1

Create a text file containing several quotations, one per line. Read every line into a collection and output one randomly selected quotation. Give a clear message when the file is empty or unavailable.

Product Catalogue

Challenge ID: PC-T17-C03 · Standards: B2.3.3, B2.5.1

A product has a code, description and price. Repeatedly ask the user for product data until no code is entered, then append each product to a text catalogue using one consistent record format. Add a menu option that reads and displays the complete catalogue.

Scaffold available
A digital product catalogue with product cards and price fields.

Till

Challenge ID: PC-T17-C04 · Standards: B2.2.2, B2.3.2, B2.3.3, B2.3.4, B2.5.1

Use a product catalogue text file to create a simple till. In trading mode, enter product codes, find matching records, display descriptions and prices, maintain a subtotal, accept payment and calculate change. In admin mode, allow the user to view the catalogue and append a new product. Separate file operations, searching and transaction logic into methods.

Scaffold available
A point-of-sale till with products, a subtotal and a receipt.