How do I write text to a file in EK9?
← File I/O · Ref: Q152
EK9 uses TextFile with output() to write text to files. Make sure the file exists, create a TextFile for it, open an output stream inside try-with-resources, and write lines using the stream.
THE FILE MUST EXIST FIRST
A TextFile is only set when its path exists and is a file. TextFile of a path that does not exist yet is unset, its output() is unset, and nothing is written - no file is created. Create the file first with FileSystemPath.createFileIfAbsent(), which returns a Result that must be checked:
path <- FileSystemPath().inCurrentWorkingDirectory("output.txt") created <- path.createFileIfAbsent()
The path must be ABSOLUTE: createFileIfAbsent on a relative FileSystemPath("output.txt") returns an error Result ("path is not absolute"), and TextFile of a relative name is always unset.
CREATING OUTPUT
Use file.output() to get a CloseableStringOutput stream:
file <- TextFile(path) try -> output <- file.output() if output? output.println("Hello, file!")
The output stream is automatically closed when the try block exits. Opening it replaces what the file held.
WRITING LINES
The output stream supports println() for writing lines of text. You can write multiple lines in sequence:
output.println("Line one") output.println("Line two")
CLOSING RESOURCES
The try-with-resources pattern ensures the file is properly flushed and closed, even if an exception occurs during writing. You never need to explicitly close the stream.
TRY WITH RESOURCES FOR OUTPUT
Just like reading, writing uses try-with-resources:
try -> output <- file.output() if output? output.println("data") catch -> ex as Exception stderr.println("Write failed: " + $ex)
The resource declaration is not a guard: if the file cannot be opened for writing, output() returns an unset value and the try body STILL runs. That is why the body checks output? before writing.
See Q151 for reading files. See Q134 for try/catch. See Q3 for stdout.
Example
defines module qa.fileio.write defines program WriteTextFileDemo() stdout <- Stdout() // === A NEW FILE MUST EXIST BEFORE TEXTFILE IS SET === notYetCreated <- TextFile("/tmp/qa-example-never-created.txt") stdout.println(`Absent file set: ${notYetCreated?}`) // createFileIfAbsent returns a Result that must be checked path <- FileSystemPath("/tmp/qa-example-output.txt") created <- path.createFileIfAbsent() stdout.println(`File ready: ${created.isOk()}`) // === CREATING A TEXTFILE FOR WRITING === file <- TextFile(path) stdout.println("Output file: " + $file) // === FILE PROPERTIES === stdout.println("Is writable: " + $file.isWritable()) // === WRITING PATTERN === // The try body runs even if output() is unset, so check output? before writing try -> output <- file.output() if output? output.println("Hello, file!") output.println("Line two") // Two lines: 13 + 9 characters including the newlines stdout.println("File length: " + $(length file))
Common mistakes
E50060 — TextFile has no toString() method. Use the $ prefix operator for string conversion. See ek9 -h E50060 for details.
Incorrect:
stdout.println(file.toString())
Correct:
stdout.println("Output file: " + $file)
E50060 — TextFile has no canWrite() method. Use isWritable() to check if the file can be written. EK9 uses descriptive method names. See ek9 -h E50060 for details.
Incorrect:
stdout.println("Is writable: " + $file.canWrite())
Correct:
stdout.println("Is writable: " + $file.isWritable())
Other ways to ask this
- How do I save data to a file in EK9?
- How do I create and write a text file in EK9?
- What is TextFile output in EK9?
Coming from another language?
Java: Files.writeString(Path, content) or BufferedWriter with try-with-resources. Python: with open('file', 'w') as f: f.write(content). Rust: fs::write('file', content). Go: os.WriteFile('file', data, perm). EK9: create the file first (FileSystemPath.createFileIfAbsent(), checked), then TextFile(path) with try -> output <- file.output() and an output? check, for safe, auto-closing file writing.
Keywords: save, stream, textfile, file, read, create, output, write, text