Axle v0.22.0

Files and I/O

std/io ships the file-and-stream API. Pick the tool by how much data you move and how you want to see it:

You want toReach forShape
read or write a small file in one callPath (readText, writeText, appendText)whole file as one string
check existence, size or delete a fileFilea path wrapper
read lines from a fileBufferedReader over a FileInputStreamone line per call
write lines or text to a fileBufferedWriter or PrintWriter over a FileOutputStreamstreamed
move raw bytesFileInputStream / FileOutputStreamone byte or a buffer per call
parse typed values from standard inputScannerone typed line per call
work in memory, for testsByteArrayInputStream / ByteArrayOutputStreama buffer
  file on disk
     │
     ├── Path::readText() ───────────────▶ string (whole file)
     │
     ├── FileInputStream ──▶ BufferedReader ──▶ readLine() ──▶ one line
     │        (bytes)          (wraps it)
     │
     └── FileOutputStream ─▶ BufferedWriter ──▶ writeLine() ─▶ file
              (bytes)           (wraps it)       (flushed by close)

Every stream class is Closeable. Pair every open with a defer close(). There is no whole-file File.readAll or writeAll: reach for Path::readText and writeText for small files, and stream the bytes for large ones.

Note Every call on this page is blocking: it returns when the kernel has the bytes, and it holds the thread it was made on. Sockets have an event-loop form; files do not (see File reads in tasks).

Read a whole file

use std::io::path::Path;
use std::lang::IOException;

fn loadText(path : string) : string ! IOException {
    return Path::from(path).readText();         // slurps the whole file
}

fn main() : i32 {
    try {
        let s : string = loadText("/etc/hostname");
        // … use s …
        return 0;
    } catch e : IOException {
        return 1;
    }
}

Path::readText() reads the entire file into a string. Use it only for files that fit in memory.

Write a whole file

use std::io::path::Path;

fn saveText(path : string, content : string) : void ! IOException {
    Path::from(path).writeText(content);        // truncates and writes
}

writeText replaces any existing content. appendText adds to the end. For streamed appends, see Append-only logging.

Existence and metadata

use std::io::File;

fn dump(path : string) : void ! IOException {
    let f : File = new File(path);
    defer f.close();
    if (!f.exists()) {
        // An absent file reads as zero bytes.
        return;
    }
    let bytes : i64 = f.length();
    // … print bytes …
}
File methodReturnsEffect
exists()booltrue when the path names an existing file; does not throw
length()i64size in bytes; 0 when the file is absent; does not throw
delete()voidremove the file; throws IOException
openRead()FileInputStreamopen for reading; throws FileNotFoundException
openWrite()FileOutputStreamopen for writing; truncates
openAppend()FileOutputStreamopen for appending
close()voidno-op: a File holds no open handle

A File is Closeable, so the compiler still wants a visible close() even though it does nothing. Pair it with defer like any other resource.

Line-by-line read

use std::io::BufferedReader;
use std::io::FileInputStream;

fn countLines(path : string) : i32 ! IOException, FileNotFoundException {
    let reader : BufferedReader = new BufferedReader(new FileInputStream(path));
    defer reader.close();

    let mut count : i32 = 0;
    // readLine() returns "" at end of stream.
    let mut line : string = reader.readLine();
    while (!line.isEmpty()) {
        count = count + 1;
        line = reader.readLine();
    }
    return count;
}

BufferedReader takes ownership of the FileInputStream it wraps: closing the reader closes the file. Construct the stream inline, in the wrapper’s constructor as above, rather than binding it to its own local. A named stream is tracked as a second resource that would demand its own close(). The inline stream belongs wholly to the reader, so one defer reader.close() covers both.

readLine() strips the trailing newline and returns "" at end of stream. A blank line in the middle of a file also reads as "", so count files that contain blank lines another way, for example with Path::readText and a newline scan.

hasMoreLines() is the explicit end-of-stream test if you want a while guard that reads better than comparing against "":

use std::io::BufferedReader;
use std::io::FileInputStream;

fn firstLine(path : string) : string ! IOException, FileNotFoundException {
    let reader : BufferedReader = BufferedReader::open(path);
    defer reader.close();
    if (reader.hasMoreLines()) {
        return reader.readLine();
    }
    return "";
}

BufferedReader::open(path) is the static shortcut that builds the file stream for you. It is the same as the inline new BufferedReader(new FileInputStream(path)).

Line-by-line write

use std::io::BufferedWriter;
use std::io::FileOutputStream;
use std::io::FileOpenMode;
use std::collections::ArrayList;

fn writeLines(
  path : string, lines : ArrayList<string>
) : void ! IOException {
    let writer : BufferedWriter = new BufferedWriter(new FileOutputStream(path, FileOpenMode::WRITE));
    defer writer.close();                       // close flushes too, and closes the wrapped stream

    let mut i : i32 = 0;
    while (i < lines.size()) {
        writer.writeLine(lines.get(i) ?? "");   // in range: never null
        i = i + 1;
    }
}

FileOpenMode decides how the file is opened:

ModeEffect
FileOpenMode::READread-only open (used by readers)
FileOpenMode::WRITEtruncate the file, then write
FileOpenMode::APPENDwrite after the existing content

writer.close() flushes the buffer. An explicit flush() is needed only when you want the bytes on disk before close, for example before a long pause.

Typed reads from standard input: Scanner

Scanner reads standard input one line at a time, and parses each line as a typed value:

use std::io::Scanner;

fn sumIntegers() : i64 ! IOException, ParseException {
    let scanner : Scanner = new Scanner();
    defer scanner.close();

    let mut sum : i64 = 0;
    while (scanner.hasNextLine()) {
        sum = sum + scanner.nextI64();
    }
    return sum;
}
Scanner methodReturnsEffect
nextLine()stringthe next line, without its newline
hasNextLine()booltrue while a line remains
nextI32() / nextI64() / nextF64()numberone line parsed as that type; throws ParseException if it is not one

Scanner has one constructor, and it binds to stdin. To parse typed values from a file, read the lines with BufferedReader and parse each one with std::text (text::parseI32 and friends).

Append-only logging

use std::io::FileOutputStream;
use std::io::FileOpenMode;
use std::io::PrintWriter;

fn appendLog(path : string, message : string) : void ! IOException {
    let writer : PrintWriter = new PrintWriter(new FileOutputStream(path, FileOpenMode::APPEND));
    defer writer.close();
    writer.println(message);                 // writes message and a newline
}

FileOpenMode::APPEND opens at the end of the file. Append mode positions every write at the end of the file.

Chunked binary copy

use std::io::FileInputStream;
use std::io::FileOutputStream;
use std::io::FileOpenMode;

fn copyStream(src : string, dst : string) : void ! IOException, FileNotFoundException {
    let input : FileInputStream = new FileInputStream(src);
    defer input.close();

    let output : FileOutputStream = new FileOutputStream(dst, FileOpenMode::WRITE);
    defer output.close();

    let mut b : i32 = input.read();          // next byte 0..255, or -1 at end
    while (b >= 0) {
        output.write(b);                 // writes the low 8 bits of b
        b = input.read();
    }
}

The byte streams are unbuffered and byte-oriented. read() returns the next byte (0 to 255), or -1 at end of stream. write(b) emits the low 8 bits of b. available() reports the bytes still left to end of file. Each byte is a separate call, which is simple but slow for large files. For bulk data, use readBytes / writeBytes with a buffer, or wrap the stream in a BufferedReader.

Copying a whole stream in one call

std::io::copy(src, dst) moves every remaining byte from an InputStream into an OutputStream and returns the number of bytes copied:

use std::io::FileInputStream;
use std::io::FileOutputStream;
use std::io::FileOpenMode;
use std::io::copy;

fn mirror(src : string, dst : string) : i64 ! IOException, FileNotFoundException {
    let input : FileInputStream = new FileInputStream(src);
    defer input.close();
    let output : FileOutputStream = new FileOutputStream(dst, FileOpenMode::WRITE);
    defer output.close();
    return copy(input, output);
}

In-memory streams

For tests, or for building a buffer without touching disk:

use std::io::ByteArrayInputStream;
use std::io::ByteArrayOutputStream;

fn copyThroughMemory(payload : string) : string ! IOException {
    let input : ByteArrayInputStream = ByteArrayInputStream::fromString(payload);
    defer input.close();

    let output : ByteArrayOutputStream = new ByteArrayOutputStream();
    defer output.close();

    let mut b : i32 = input.read();              // next byte, or -1 at end
    while (b >= 0) {
        output.write(b);
        b = input.read();
    }
    return output.toString();
}

ByteArrayInputStream::fromString(s) copies a string’s bytes into an in-memory read cursor. read() returns the next byte, or -1 at the end, and available(), skip(), reset() and close() complete the input side. The constructor new ByteArrayInputStream(data, len) wraps an existing i8[] buffer of len bytes without copying it.

ByteArrayOutputStream collects written bytes. toString() reads them back as a string, toByteArray() as an i8[], and size() reports the count.

Console output: PrintWriter

PrintWriter wraps a FileOutputStream and adds print, println and printf:

use std::io::PrintWriter;
use std::io::FileOutputStream;

fn report(out : PrintWriter) : void ! IOException {
    out.println("== summary ==");
    out.print("count = ");
    out.println((42).toString());
}

printf takes a single format string; it does not format arguments. Build the text with + or a StringBuilder before the call.

For plain standard output and error, the prelude’s print, println, eprint and eprintln are the simpler choice: they need no stream object.

Whole-file copy

use std::io::path::Path;

fn copy(src : string, dst : string) : void ! IOException {
    Path::from(dst).writeText(Path::from(src).readText());
}

Path also has a direct copy(to) method. Either form is fine for small files. For large files, use the chunked copy above so the content is not held in RAM all at once.

Paths: Path

std::io::path ships a Path class for lexical path work and direct file operations:

use std::io::path::Path;

fn main() : i32 ! IOException {
    let p : Path = Path::from("/tmp/notes/todo.txt");

    let dir : Path = p.parent();              // /tmp/notes
    dir.mkdirs();                             // create, parents included

    p.writeText("first line\n");
    p.appendText("second line\n");
    let text : string = p.readText();

    if (!p.exists() || !p.isFile())        { return 1; }
    if (!p.extension().equals(".txt"))     { return 2; }
    if (!p.fileName().equals("todo.txt"))  { return 3; }

    p.delete();
    return 0;
}
GroupMethods
BuildPath::from(s), Path::cwd(), Path::exe()
Lexicalparent(), join(part), fileName(), extension(), stripExtension(), normalize(), isAbsolute(), toString()
Queryexists(), isFile(), isDirectory(), size(), lastModified()
ContentreadText(), writeText(s), appendText(s)
Filesystemmkdir(), mkdirs(), delete(), rename(to), copy(to)

Lexical operations accept both / and \ as separators on input, and emit /. size() and lastModified() throw IOException, while exists(), isFile() and isDirectory() answer without throwing.

Patterns

Atomic write through a temporary file

use std::io::path::Path;

fn writeAtomic(path : string, content : string) : void ! IOException {
    let tmp : Path = Path::from(path + ".tmp");
    tmp.writeText(content);
    tmp.rename(path);                           // rename over the target
}

Writing to a temporary file and renaming it over the target is the standard way to avoid leaving a half-written file behind.

Read, process, write

use std::io::path::Path;

fn transformText(raw : string) : string {
    return raw.toUpperCase();
}

fn transform(src : string, dst : string) : void ! IOException {
    let raw : string = Path::from(src).readText();
    let result : string = transformText(raw);
    Path::from(dst).writeText(result);
}

Path::readText and writeText open, transfer and close in one call, so the whole-file case needs no defer.

File reads in tasks

A file read blocks in the kernel, and it runs on the carrier: a task that reads holds that thread until the read returns. Reads spawned onto tasks that share a carrier run one after another. Reads spread over several carriers by the pool run side by side. spawn gives each read a frame of its own, but the reads overlap only as far as the pool places them.

A file has no readiness to report. There is no descriptor a poll(2) call can subscribe to, so unlike a socket it has no await form. Overlap for sockets comes from the reactor, see Async I/O.

Common pitfalls

Forgetting defer close() on a stream

use std::io::FileInputStream;

fn leak(path : string) : i32 ! IOException, FileNotFoundException {
    let input : FileInputStream = new FileInputStream(path);
    return input.read();                        // E0511: no close() on this path
}

You cannot actually forget: a Closeable resource with no visible close() on a path is rejected at compile time with E0511, not leaked at run time. Pair the open with a defer close():

use std::io::FileInputStream;

fn ok(path : string) : i32 ! IOException, FileNotFoundException {
    let input : FileInputStream = new FileInputStream(path);
    defer input.close();
    return input.read();
}

The whole-file helpers Path::readText and writeText close their own handle, so they need no defer.

Catching IOException and continuing

use std::io::path::Path;

fn loadText(path : string) : string ! IOException {
    return Path::from(path).readText();
}

fn fragile() : string {
    try {
        return loadText("/etc/missing");
    } catch e : IOException {
        return "";                              // looks safe …
    }
}

"" is a poor sentinel: it cannot tell “file empty” from “file missing”. Either propagate the exception, or return a record that names the outcome. A struct is the right shape for that: plain data with no identity, copied by value, built from a literal.

use std::io::path::Path;

fn loadText(path : string) : string ! IOException {
    return Path::from(path).readText();
}

struct LoadResult {
    ok      : bool;
    content : string;
}

fn tryLoad(path : string) : LoadResult {
    try {
        return LoadResult { ok: true, content: loadText(path) };
    } catch e : IOException {
        return LoadResult { ok: false, content: "" };   // the miss is explicit in `ok`
    }
}

The caller reads result.ok to tell a real miss from an empty file, instead of overloading "" to mean both.

Using readText on unbounded input

use std::io::path::Path;

fn dangerous(path : string) : string ! IOException {
    return Path::from(path).readText();         // fine for config files; not for logs
}

readText pulls the whole file into a string. For files larger than RAM, switch to chunked or line-by-line reads.

Limits / Uncabled

FeatureStateWorkaround
Whole-file File.readAll / writeAllNot providedPath::readText / writeText for small files; streams for large ones
Scanner on a fileNot provided: its only constructor binds stdinBufferedReader plus std::text parsers
Asynchronous file I/O (await on a read or write)Not provided: files have no readiness to wait onRun file work in a spawned task, or use sockets for overlap
Stream-object form of stdout or stderrPrintWriter wraps a FileOutputStream onlyprint, println, eprint, eprintln from the prelude
PrintWriter.printf with argumentsTakes one format string; no argument listBuild the text first with + or StringBuilder
Random access (seek, positioned reads)Not provided in std/ioRead the bytes you need through a stream, or work on an in-memory copy

See also

iofilesfilesystemstreams