CodeIEB
Theory Notes/🗄️ Topic 4: Data & Information Management, Solution Development/11.4.7
11.4.7Grade 11

Persistence: Working with Text Files

Making your program's data survive after it closes — reading and writing text files to secondary storage.

Core text file operations:

OperationPurpose
CreateMake a brand new text file, ready to write to
AppendAdd new content to the end of an existing file, without erasing what's already there
ReadRetrieve the content already stored in the file

Text files may store data in different structural formats:

  • Multiple lines with fields related to the SAME data structure — e.g. every line represents one Learner record, with fields separated by a delimiter.
  • Multiple lines with fields related to DIFFERENT data structures — e.g. a file that mixes different record types, requiring your code to identify which type each line represents before processing it.

Example

Text file content (each line = one Learner, fields separated by #): Ana#17#11 Ben#18#12 Reading this file: for each line, split on '#' to extract name, age and grade, then create a Learner object for each and store them in an array of objects.

Testing if a file exists before trying to read it prevents a runtime crash — this typically requires exception handling (see 11.4.14) to gracefully deal with a missing or inaccessible file.

💡 Exam Tip

Always plan your file's delimiter and structure BEFORE writing your read/write code — inconsistent formatting between writing and reading a file is one of the most common practical exam bugs.