File and Dir
import "std/io" (included in import "std") · namespace std.io
File reads and writes files; Dir creates, lists and removes directories. Reading a file that cannot be read (it is missing, a directory, or not permitted) throws an IOError that says why; readOr(fallback) returns the fallback instead. Writing methods return false when they fail, and size() returns -1 for a missing file.
import "std"
fn main() {
let dir = Path.combine(Dir.temp(), "grav-docs-demo")
Dir.create(dir)
let f = new File(Path.combine(dir, "notes.txt"))
f.writeLine("first")
f.appendLine("second")
print(f.exists())
print(f.size())
print(f.readLines())
print(Str.trim(f.read()))
let copy = Path.combine(dir, "copy.txt")
f.copyTo(copy)
let names = Dir.list(dir)
Sort.sort(names)
print(names)
new File(copy).delete()
f.delete()
print(Dir.remove(dir))
print(new File(copy).readOr("(gone)"))
try {
new File(copy).read()
} catch (e: IOError) {
print("read failed: ${Str.contains(e.message(), "No such file")}")
}
}true
13
["first", "second"]
first
second
["copy.txt", "notes.txt"]
true
(gone)
read failed: trueread/write/appendwork with text;readBinary/writeBinarywith raw bytes (binary, seeBytes).writereplaces the file;appendadds to its end. Both create it if needed.modified()is the last change time in Unix seconds.Dir.listreturns names (not full paths), sorted.Dir.createcreates the directory and any missing parents;Dir.removeremoves an empty directory andDir.removeAlla whole tree.- Paths are plain strings;
Pathbuilds and takes them apart.
Folders, globs and large files
Dir.walk(path) lists every file under a folder; Dir.find(path, "*.grav") filters them by a glob pattern; Dir.size adds up their sizes. For files too large to read at once, FileReader reads one line at a time and FileWriter writes through a buffer.
import "std"
fn main() {
let root = Path.combine(Dir.temp(), "grav-docs-tree")
Dir.removeAll(root)
Dir.create(Path.combine(root, "src/util"))
new File(Path.combine(root, "src/main.grav")).write("fn main() { }\n")
new File(Path.combine(root, "src/util/text.grav")).write("// helpers\n")
new File(Path.combine(root, "notes.txt")).write("todo\n")
for (f in Dir.find(root, "*.grav")) { print(f[root.length + 1..]) }
let w = new FileWriter(Path.combine(root, "log.txt"))
for (i in 1..=3) { w.writeLine("line ${i}") }
w.close()
let r = new FileReader(Path.combine(root, "log.txt"))
print(r.readLine())
r.forEachLine(fn(line) { print("then: " + line) })
print(Dir.removeAll(root))
}src/main.grav
src/util/text.grav
line 1
then: line 2
then: line 3
trueFileReader.readLine() returns a string?: the next line without its line break, or null at the end of the file.
Glob patterns
Dir.glob("src/**/*.grav") returns the paths matching a pattern, sorted: * is any text within one name, ? one character, [abc] one of, and ** any number of directories. As in a shell, * and ? skip names starting with "." (write .* for those), and links to directories are not followed. Dir.find(dir, "*.grav") matches names only, anywhere under dir.
API
class File
Constructors
new File(path: string)
Methods
fn name() -> string— The path the file was opened with.fn path() -> string— The path the file was opened with.fn exists() -> bool— Whether a regular file exists at the path.fn size() -> long— Size in bytes (-1 if it does not exist); 64-bit, so large files are fine.fn modified() -> long— Last modification time (unix seconds), or -1.fn setModified(unixSeconds: long) -> bool— Sets the last modification (and access) time tounixSeconds, which may lie in the future (a cache can stamp a file with when it expires); false when the file is missing or cannot be changed.fn read() -> string— The whole file as text; IOError when it cannot be read (missing, a directory, no permission).fn readOr(fallback: string) -> string— The whole file as text, orfallbackwhen it cannot be read.fn write(data: string) -> bool— Replaces the file's contents withdata; whether it worked.fn append(data: string) -> bool— Addsdataat the end of the file (creating it); whether it worked.fn writeLine(line: string) -> bool— Adds a line (with "\n") at the end of the file; whether it worked.fn appendLine(line: string) -> bool— Adds a line (with "\n") at the end of the file; whether it worked.fn readLines() -> Array<string>— Lines of the file (handles \n and \r\n); IOError when it cannot be read.fn lines() -> FileReader— The lines one at a time, read as the loop asks for them: for files too big to hold.for (line in new File("big.log").lines()).fn writeLines(lines: Array<string>) -> bool— Replaces the contents with the lines joined by "\n"; whether it worked.fn readBinary() -> binary— The whole file as raw bytes (NUL-safe); IOError when it cannot be read.fn writeBinary(data: binary) -> bool— Replaces the file's contents with raw bytes; whether it worked.fn appendBinary(data: binary) -> bool— Adds raw bytes at the end of the file; whether it worked.fn delete() -> bool— Deletes the file; whether it worked.fn copyTo(dest: string) -> bool— Byte-for-byte copy (works for binary files).fn moveTo(dest: string) -> bool— Renames or moves the file todest; whether it worked.
class Dir
Directory operations on paths.
Static members
static fn exists(path: string) -> bool— Whether a directory exists atpath.static fn create(path: string) -> bool— Creates the directory and any missing parents (like mkdir -p).static fn remove(path: string) -> bool— Removes an empty directory.static fn list(path: string) -> Array<string>— Entry names (not paths), sorted, without "." and "..".static fn isFile(path: string) -> bool— Whether a regular file exists atpath.static fn current() -> string— The working directory.static fn change(path: string) -> bool— Changes the working directory; whether it worked.static fn temp() -> string— The system temporary directory ($TMPDIR, else /tmp).static fn entries(path: string) -> DirEntries— Entry names (not paths) one at a time, in the order the system lists them (unsorted), without "." and "..": for directories too big to list at once.static fn files(path: string) -> DirFiles— Every file underpath, recursively, one at a time (unsorted, as paths starting withpath): walk() without holding them all.static fn walk(path: string) -> Array<string>— Every file underpath, recursively, as paths starting withpath, sorted.static fn find(path: string, pattern: string) -> Array<string>— The files underpath(recursively) whose name matches a glob pattern such as "*.grav" or "test_?.txt" (* any text, ? one character, [abc] one of).static fn glob(pattern: string) -> Array<string>— The paths matching a glob pattern, sorted:*any text within one name,?one character,[abc]one of, and**any number of directories ("src/**/*.grav", "logs/*.log", "/etc/*.conf"). As in a shell,*and?do not match a leading "." (write ".*" for hidden files), and links to directories are not followed.static fn removeAll(path: string) -> bool— Removes a directory and everything in it (like rm -r); whether it worked. Symbolic links are removed, not followed.static fn isLink(path: string) -> bool— Whetherpathis a symbolic link.static fn size(path: string) -> long— The total size in bytes of the files underpath.
class FileReader implements Iterator<string>
Reads a text file one line at a time, without loading it all: for large files.
for (line in new FileReader("big.log")) { ... } // closed at the end let r = new FileReader("big.log") while (true) { let line = r.readLine(); if (line == null) { break } ... } r.close()
Constructors
new FileReader(path: string)— Openspathfor reading; IOError when it cannot be opened.
Static members
static fn stdin() -> FileReader— Standard input, line by line (see IO.lines).
Fields
readonly path: string— The path being read.
Methods
fn readLine() -> string?— The next line without its line break (\n or \r\n), or null at the end of the file.fn hasNext() -> bool— Whether there is another line (whatfor (line in reader)asks; the file is closed at its end).fn next() -> string— The next line (StateError at the end of the file).fn forEachLine(f: fn(string))— Calls f with each remaining line, then closes the file.fn close()— Closes the file (safe to call twice).
class DirEntries implements Iterator<string>
A directory's entry names, read as they are asked for (see Dir.entries).
Constructors
new DirEntries(path: string)
Methods
fn hasNext() -> boolfn next() -> stringfn close()— Stops reading (done by itself at the end).
class DirFiles implements Iterator<string>
The files under a directory, recursively, found as they are asked for (see Dir.files).
Constructors
new DirFiles(path: string)
Methods
fn hasNext() -> boolfn next() -> string
class FileWriter
Writes a file piece by piece through a buffer: for large or incremental output.
Constructors
new FileWriter(path: string, append: bool)— Openspathfor writing, replacing it, or adding to its end whenappendis true; IOError when it cannot be opened.new FileWriter(path: string)— Openspathfor writing, replacing it.
Fields
readonly path: string— The path being written.
Methods
fn write(text: string) -> FileWriter— Writes text; IOError after close().fn writeLine(text: string) -> FileWriter— Writes text and a line break.fn flush()— Sends buffered text to the file now.fn close()— Flushes and closes the file (safe to call twice).