← Back to lessons

34 Reading and Writing to Files

Hard

In cangjie we use the classes StringReader and StringWriter to avoid manually manipulating Bytes

Here we create ByteArrayStream() and use stringWriter to write strings directly into the stream. We can then pass this into a file, or print to console.

Reading is a similar process, however the return types can differ. You can see with readln we return an option type because there may not be a line that can be read.

reading-writing-files.cj
import std.fs.*
import std.io.*

main() {
    let byteArrayStream = ByteArrayStream()
    let stringWriter = StringWriter(byteArrayStream)

    stringWriter.write("Hello")
    stringWriter.writeln(", world!")
    stringWriter.writeln("this is being written")
    stringWriter.flush()

    let file = File.create("./tempFile.txt")
    file.write(byteArrayStream.readToEnd())

    let file2 = File.openRead("./tempFile.txt")
    let stringReader = StringReader(file2)
    println(stringReader.readln().getOrThrow())
    println(stringReader.readToEnd())
}

// Output:
// Hello, world!
// this is being written