Files
File Constructors
// construct from Uri
f := File.make(`dir/foo.txt`)
f := `dir/foo.txt`.toFile
// construct from OS specific path
f := File.os("bin\\command.exe")
f := File.os("bin" + File.sep + "command.exe")
// construct File instance resolved against base directory
f := dir + `foo.txt`
f := dir + `subdir/foo.txt`
f := dir + `../foo.txt`
File Naming
f := `/files/today/foo.txt`.toFile
f.uri -> `/files/today/foo.txt`
f.path -> ["files", "today", "foo.txt"]
f.pathStr -> "/files/today/foo.txt"
f.name -> "foo.txt"
f.basename -> "foo"
f.ext -> "txt"
f.parent.path -> ["files", "today"]
f.osPath
Working with Directories
// check if file is a directory
f.isDir
// list all files in a directory (files and dirs)
files := dir.list
// list file names in a directory
filenames := Str[,]
dir.list.map(filenames) |File f->Str| { return f.name }
// get sub directories (filter out files)
subdirs := dir.list.findAll |File f->Bool| { return f.isDir }
// get child files (filter out sub directories)
files := dir.list.findAll |File f->Bool| { return !f.isDir }
// create directory (uri must end in / slash)
dir.create
Reading Files
// read entire text file into a string
s := f.readAllStr
// read entire text file into a list of string lines
lines := f.readAllLines
// process each line
f.eachLine |Str line| { processLine(line) }
// read entire binary file into memory
buf := f.readAllBuf
// read file using encoding other than UTF-8
in := f.in
in.charset = Charset.utf16BE
lines := in.readAllLines
in.close
// read binary file stream
in := f.in
b := in.read
s := in.readU2
i := in.readU4
in.close
// serialize object from file
obj := f.readObj
Writing Files
// create empty file (uri must not end in / slash)
f.create
// write text file (overwrites existing)
f.out.printLine("hello").close
// append to existing text file
f.out(true).printLine("hello").close
// write text file using encoding other than UTF-8
out := f.out
out.charset = Charset.make("ISO-8859-2")
out.printLine("hello world")
out.close
// write list of lines to file
out := f.out
lines.each |Str line| { out.printLine(line) }
out.close
// write binary file
out := f.out
out.writeI4(0xcafebabe)
out.close
// serialize object to file
f.writeObj(obj, ["indent":2])