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. Create a TextFile with the target path, open an output stream inside try-with-resources, and write lines using the stream.
CREATING OUTPUT
Use file.output() to get a CloseableStringOutput stream:
file <- TextFile("output.txt") try -> output <- file.output() output.println("Hello, file!")
The output stream is automatically closed when the try block exits.
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 the try guard pattern:
try -> output <- file.output() // write data here catch -> ex as Exception stderr.println("Write failed: " + $ex)
If the file cannot be opened for writing, output() returns an unset value and the try body is skipped.
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() // === CREATING A TEXTFILE FOR WRITING === file <- TextFile("/tmp/qa-example-output.txt") stdout.println("Output file: " + $file) // === FILE PROPERTIES === stdout.println("Is writable: " + $file.isWritable()) // === WRITING PATTERN === // The standard pattern for writing: // try // -> output <- file.output() // output.println("Hello, file!") // catch // -> ex as Exception // stderr.println("Write failed") // TextFile also supports checking file state stdout.println("File length: " + $file.length())
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: TextFile('file') with try -> output <- file.output() for safe, auto-closing file writing.
Keywords: output, create, read, file, textfile, stream, save, text, write