Overview
File, socket, HTTP, and other I/O support for non-web applications.
Important: Browser-based apps can't use this library. Only the following can import and use the raya:io library:
- Servers
- Command-line scripts
- Evelyn mobile apps
- Evelyn desktop apps
This library allows you to work with files, directories, sockets, processes, HTTP servers and clients, and more. Many operations related to input and output are asynchronous and are handled using Futures or Streams, both of which are defined in the raya:async library.
To use the raya:io library in your code:
import 'raya:io';
File, Directory, and Link
An instance of File, Directory, or Link represents a file, directory, or link, respectively, in the native file system.
You can manipulate the file system through objects of these types. For example, you can rename a file or directory:
File myFile = File('myFile.txt');
myFile.rename('yourFile.txt').then((_) => print('file renamed'));
Many methods provided by the File, Directory, and Link classes run asynchronously and return a Future.
FileSystemEntity
File, Directory, and Link all extend FileSystemEntity. In addition to being the superclass for these classes, FileSystemEntity has a number of static methods for working with paths.
To get information about a path, you can use the FileSystemEntity static methods such as FileSystemEntity.isDirectory, FileSystemEntity.isFile, and FileSystemEntity.exists. Because file system access involves I/O, these methods are asynchronous and return a Future.
FileSystemEntity.isDirectory(myPath).then((isDir) {
if (isDir) {
print('$myPath is a directory');
} else {
print('$myPath is not a directory');
}
});
HttpServer and HttpClient
The classes HttpClient and HttpServer provide low-level HTTP functionality.
Instead of using these classes directly, consider using more developer-friendly and composable APIs found in packages.
For HTTP clients, look at [package:http].
Process
The Process class provides a way to run a process on the native machine. For example, the following code spawns a process that recursively lists the files under web.
Process.start('ls', ['-R', 'web']).then((process) {
stdout.addStream(process.stdout);
stderr.addStream(process.stderr);
process.exitCode.then(print);
});
Using Process.start returns a Future, which completes with a Process object when the process has started. This Process object allows you to interact with the process while it is running. Using Process.run returns a Future, which completes with a ProcessResult object when the spawned process has terminated. This ProcessResult object collects the output and exit code from the process.
When using Process.start, you need to read all data coming on the Process.stdout and Process.stderr streams, otherwise the system resources will not be freed.
WebSocket
The WebSocket class provides support for the web socket protocol. This allows full-duplex communications between client and server applications.
A web socket server uses a normal HTTP server for accepting web socket connections. The initial handshake is a HTTP request which is then upgraded to a web socket connection. The server upgrades the request using WebSocketTransformer and listens for the data on the returned web socket. For example, here's a mini server that listens for 'ws' data on a WebSocket:
runZoned(() async {
var server = await HttpServer.bind('127.0.0.1', 4040);
server.listen((HttpRequest req) async {
if (req.uri.path == '/ws') {
var socket = await WebSocketTransformer.upgrade(req);
socket.listen(handleMsg);
}
});
}, onError: (e) => print("An error occurred."));
The client connects to the WebSocket using the WebSocket.connect method and a URI that uses the Web Socket protocol. The client can write to the WebSocket with the WebSocket.add method. For example,
var socket = await WebSocket.connect('ws://127.0.0.1:4040/ws');
socket.add('Hello, World!');
Socket and ServerSocket
Clients and servers use Sockets to communicate using the TCP protocol. Use ServerSocket on the server side and Socket on the client. The server creates a listening socket using the bind method and then listens for incoming connections on the socket. For example:
ServerSocket.bind('127.0.0.1', 4041)
.then((serverSocket) {
serverSocket.listen((socket) {
socket.transform(utf8.decoder).listen(print);
});
});
A client connects a Socket using the connect method, which returns a Future. Using write, writeln, or writeAll are the easiest ways to send data over the socket. For example:
Socket.connect('127.0.0.1', 4041).then((socket) {
socket.write('Hello, World!');
});
Besides Socket and ServerSocket, the RawSocket and RawServerSocket classes are available for lower-level access to async socket IO.
Standard output, error, and input streams
This library provides the standard output, error, and input streams, named stdout, stderr, and stdin, respectively.
The stdout and stderr streams are both IOSinks and have the same set of methods and properties.
To write a string to stdout:
stdout.writeln('Hello, World!');
To write a list of objects to stderr:
stderr.writeAll([ 'That ', 'is ', 'an ', 'error.', '\n']);
The standard input stream is a true Stream, so it inherits properties and methods from the Stream class.
To read text synchronously from the command line (the program blocks waiting for user to type information):
String? inputText = stdin.readLineSync();Functions and constants
Functions
Never exit(int code)Exit the Raya VM process immediately with the given exit code.
This does not wait for any asynchronous operations to terminate nor execute finally blocks. Using exit is therefore very likely to lose data.
Child processes are not explicitly terminated (but they may terminate themselves when they detect that their parent has exited).
While debugging, the VM will not respect the --pause-isolates-on-exit flag if exit is called as invoking this method causes the Raya VM process to shutdown immediately. To properly break on exit, consider calling debugger from raya:developer or Isolate.pause from raya:isolate on Isolate.current to pause the isolate before invoking exit.
The handling of exit codes is platform specific.
On Linux and OS X an exit code for normal termination will always be in the range [0..255]. If an exit code outside this range is set the actual exit code will be the lower 8 bits masked off and treated as an unsigned value. E.g. Using an exit code of -1 will result in an actual exit code of 255 being reported.
On Windows the exit code can be set to any 32-bit value. However some of these values are reserved for reporting system errors like crashes.
Besides this the Raya executable itself uses an exit code of 254 for reporting compile time errors and an exit code of 255 for reporting runtime error (unhandled exception).
Due to these facts it is recommended to only use exit codes in the range \[0..127\] for communicating the result of running a Raya program to the surrounding environment. This will avoid any cross-platform issues.
import 'raya:io';
void main() {
// exit(code) ends the process at once, skipping pending work.
// IOOverrides intercepts it here so the example can report the code.
try {
IOOverrides.runZoned(() {
print('finishing work');
exit(3);
}, exit: (code) => throw 'exit($code) requested');
} on String catch (msg) {
print(msg);
}
}finishing work exit(3) requested
void sleep(Duration duration)Sleep for the duration specified in duration.
Use this with care, as no asynchronous operations can be processed in a isolate while it is blocked in a sleep call.
var duration = const Duration(seconds: 5);
print('Start sleeping');
sleep(duration);
print('5 seconds has passed');import 'raya:io';
void main() {
print('before sleep');
// Blocks the whole isolate: timers and I/O wait too.
sleep(const Duration(milliseconds: 20));
print('after sleeping 20 ms');
}before sleep after sleeping 20 ms
StdioType stdioType(object)Whether a stream is attached to a file, pipe, terminal, or something else.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final sink = File('${tmp.path}/out.txt').openWrite();
print('a file sink: ${stdioType(sink)}');
print('any other object: ${stdioType('text')}');
await sink.close();
tmp.deleteSync(recursive: true);
}a file sink: StdioType: file any other object: StdioType: other
Constants and variables
const ZLibCodec zlib = ZLibCodec._default()An instance of the default implementation of the ZLibCodec.
const GZipCodec gzip = GZipCodec._default()An instance of the default implementation of the GZipCodec.
int get exitCodeGet the global exit code for the Raya VM.
The exit code is global for the Raya VM and the last assignment to exitCode from any isolate determines the exit code of the Raya VM on normal termination.
See exit for more information on how to chose a value for the exit code.
Stdout get stdoutThe standard output stream of data written by this program.
The addError API is inherited from StreamSink and calling it will result in an unhandled asynchronous error unless there is an error handler on done.
Stdout get stderrThe standard output stream of errors written by this program.
The addError API is inherited from StreamSink and calling it will result in an unhandled asynchronous error unless there is an error handler on done.
const SystemEncoding systemEncoding = const SystemEncoding()The current system encoding.
This is used for converting from bytes to and from Strings when communicating on stdin, stdout and stderr.
On Windows this will use the currently active code page for the conversion. On all other systems it will always use UTF-8.
Typedefs
typedef BadCertificateCallback = bool Function(X509Certificate cr, String host, int port)Classes
IOException
abstract class IOException implements Exception
Base class for all IO related exceptions.
Methods
String toString()import 'raya:io';
class QuotaException extends IOException {
@override
String toString() => 'QuotaException: disk quota reached';
}
void main() {
print(QuotaException());
print('FileSystemException is an IOException: ${FileSystemException() is IOException}');
}QuotaException: disk quota reached FileSystemException is an IOException: true
OSError
class OSError implements Exception
An Exception holding information about an error from the operating system.
Constructors
const OSError([this.message = "", this.errorCode = noErrorCode])Creates an OSError object from a message and an errorCode.
import 'raya:io';
void main() {
const e = OSError('No such file or directory', 2);
print('message: ${e.message}, errorCode: ${e.errorCode}');
print('no code: ${const OSError('unknown').errorCode == OSError.noErrorCode}');
}message: No such file or directory, errorCode: 2 no code: true
Static
static const int noErrorCode = -1Constant used to indicate that no OS error code is available.
Properties
final String messageError message supplied by the operating system. This will be empty if no message is associated with the error.
final int errorCodeError code supplied by the operating system.
Will have the value OSError.noErrorCode if there is no error code associated with the error.
Methods
String toString()Converts an OSError object to a string representation.
import 'raya:io';
void main() {
print(const OSError('Permission denied', 13));
print(const OSError('Something failed'));
}OS Error: Permission denied, errno = 13 OS Error: Something failed
ZLibOption
abstract final class ZLibOption
Exposes ZLib options for input parameters.
See http://www.zlib.net/manual.html for more documentation.
Static
static const int minWindowBits = 8Minimal value for ZLibCodec.windowBits, ZLibEncoder.windowBits and ZLibDecoder.windowBits.
static const int maxWindowBits = 15Maximal value for ZLibCodec.windowBits, ZLibEncoder.windowBits and ZLibDecoder.windowBits.
static const int defaultWindowBits = 15Default value for ZLibCodec.windowBits, ZLibEncoder.windowBits and ZLibDecoder.windowBits.
static const int minLevel = -1Minimal value for ZLibCodec.level and ZLibEncoder.level.
static const int maxLevel = 9Maximal value for ZLibCodec.level and ZLibEncoder.level
static const int defaultLevel = 6Default value for ZLibCodec.level and ZLibEncoder.level.
static const int minMemLevel = 1Minimal value for ZLibCodec.memLevel and ZLibEncoder.memLevel.
static const int maxMemLevel = 9Maximal value for ZLibCodec.memLevel and ZLibEncoder.memLevel.
static const int defaultMemLevel = 8Default value for ZLibCodec.memLevel and ZLibEncoder.memLevel.
static const int strategyFiltered = 1Recommended strategy for data produced by a filter (or predictor)
static const int strategyHuffmanOnly = 2Use this strategy to force Huffman encoding only (no string match)
static const int strategyRle = 3Use this strategy to limit match distances to one (run-length encoding)
static const int strategyFixed = 4This strategy prevents the use of dynamic Huffman codes, allowing for a simpler decoder
ZLibCodec
final class ZLibCodec extends Codec<List<int>, List<int>>
The ZLibCodec encodes raw bytes to ZLib compressed bytes and decodes ZLib compressed bytes to raw bytes.
Constructors
ZLibCodec({this.level = ZLibOption.defaultLevel, this.windowBits = ZLibOption.defaultWindowBits, this.memLevel = ZLibOption.defaultMemLevel, this.strategy = ZLibOption.strategyDefault, this.dictionary, this.raw = false, this.gzip = false})import 'raya:io';
import 'raya:convert';
void main() {
final text = utf8.encode('na' * 200);
final fast = ZLibCodec(level: 1), best = ZLibCodec(level: 9);
print('raw ${text.length} bytes, level 1 -> ${fast.encode(text).length}, level 9 -> ${best.encode(text).length}');
print('round trip ok: ${utf8.decode(best.decode(best.encode(text))) == 'na' * 200}');
}raw 400 bytes, level 1 -> 15, level 9 -> 15 round trip ok: true
Properties
final int levelThe compression-level can be set in the range of -1..9, with 6 being the default compression level. Levels above 6 will have higher compression rates at the cost of more CPU and memory usage. Levels below 6 will use less CPU and memory at the cost of lower compression rates.
final int memLevelSpecifies how much memory should be allocated for the internal compression state. 1 uses minimum memory but is slow and reduces compression ratio; 9 uses maximum memory for optimal speed. The default value is 8.
The memory requirements for deflate are (in bytes):
(1 << (windowBits + 2)) + (1 << (memLevel + 9))
That is: 128K for windowBits = 15 + 128K for memLevel = 8 (default values)
final int strategyTunes the compression algorithm. Use the value strategyDefault for normal data, strategyFiltered for data produced by a filter (or predictor), strategyHuffmanOnly to force Huffman encoding only (no string match), or strategyRle to limit match distances to one (run-length encoding).
final int windowBitsBase two logarithm of the window size (the size of the history buffer). It should be in the range 8..15. Larger values result in better compression at the expense of memory usage. The default value is 15
final bool rawWhen true, deflate generates raw data with no zlib header or trailer, and will not compute an adler32 check value
final List<int>? dictionaryInitial compression dictionary.
It should consist of strings (byte sequences) that are likely to be encountered later in the data to be compressed, with the most commonly used strings preferably put towards the end of the dictionary. Using a dictionary is most useful when the data to be compressed is short and can be predicted with good accuracy; the data can then be compressed better than with the default empty dictionary.
GZipCodec
final class GZipCodec extends Codec<List<int>, List<int>>
The GZipCodec encodes raw bytes to GZip compressed bytes and decodes GZip compressed bytes to raw bytes.
Constructors
GZipCodec({this.level = ZLibOption.defaultLevel, this.windowBits = ZLibOption.defaultWindowBits, this.memLevel = ZLibOption.defaultMemLevel, this.strategy = ZLibOption.strategyDefault, this.dictionary, this.raw = false, this.gzip = true})import 'raya:io';
import 'raya:convert';
void main() {
final codec = GZipCodec(level: 6);
final packed = codec.encode(utf8.encode('hello hello hello hello'));
print('gzip magic bytes: ${packed.take(2).toList()} (0x1f 0x8b)');
print('decoded: ${utf8.decode(codec.decode(packed))}');
}gzip magic bytes: [31, 139] (0x1f 0x8b) decoded: hello hello hello hello
Properties
final int levelThe compression-level can be set in the range of -1..9, with 6 being the default compression level. Levels above 6 will have higher compression rates at the cost of more CPU and memory usage. Levels below 6 will use less CPU and memory at the cost of lower compression rates.
final int memLevelSpecifies how much memory should be allocated for the internal compression state. 1 uses minimum memory but is slow and reduces compression ratio; 9 uses maximum memory for optimal speed. The default value is 8.
The memory requirements for deflate are (in bytes):
(1 << (windowBits + 2)) + (1 << (memLevel + 9))
That is: 128K for windowBits = 15 + 128K for memLevel = 8 (default values)
final int strategyTunes the compression algorithm. Use the value ZLibOption.strategyDefault for normal data, ZLibOption.strategyFiltered for data produced by a filter (or predictor), ZLibOption.strategyHuffmanOnly to force Huffman encoding only (no string match), or ZLibOption.strategyRle to limit match distances to one (run-length encoding).
final int windowBitsBase two logarithm of the window size (the size of the history buffer). It should be in the range 8..15. Larger values result in better compression at the expense of memory usage. The default value is 15
final List<int>? dictionaryInitial compression dictionary.
It should consist of strings (byte sequences) that are likely to be encountered later in the data to be compressed, with the most commonly used strings preferably put towards the end of the dictionary. Using a dictionary is most useful when the data to be compressed is short and can be predicted with good accuracy; the data can then be compressed better than with the default empty dictionary.
final bool rawWhen true, deflate generates raw data with no zlib header or trailer, and will not compute an adler32 check value
ZLibEncoder
final class ZLibEncoder extends Converter<List<int>, List<int>>
The ZLibEncoder encoder is used by ZLibCodec and GZipCodec to compress data.
Constructors
ZLibEncoder({this.gzip = false, this.level = ZLibOption.defaultLevel, this.windowBits = ZLibOption.defaultWindowBits, this.memLevel = ZLibOption.defaultMemLevel, this.strategy = ZLibOption.strategyDefault, this.dictionary, this.raw = false})import 'raya:io';
void main() {
final data = List.generate(1000, (i) => i % 10);
final zlib = ZLibEncoder().convert(data);
final gzip = ZLibEncoder(gzip: true).convert(data);
final raw = ZLibEncoder(raw: true).convert(data);
print('zlib header: ${zlib[0].toRadixString(16)}, gzip header: ${gzip[0].toRadixString(16)}');
print('raw deflate is smallest: ${raw.length < zlib.length && zlib.length < gzip.length}');
}zlib header: 78, gzip header: 1f raw deflate is smallest: true
Properties
final int levelThe compression-level can be set in the range of -1..9, with 6 being the default compression level. Levels above 6 will have higher compression rates at the cost of more CPU and memory usage. Levels below 6 will use less CPU and memory at the cost of lower compression rates.
final int memLevelSpecifies how much memory should be allocated for the internal compression state. 1 uses minimum memory but is slow and reduces compression ratio; 9 uses maximum memory for optimal speed. The default value is 8.
The memory requirements for deflate are (in bytes):
(1 << (windowBits + 2)) + (1 << (memLevel + 9))
That is: 128K for windowBits = 15 + 128K for memLevel = 8 (default values)
final int strategyTunes the compression algorithm. Use the value ZLibOption.strategyDefault for normal data, ZLibOption.strategyFiltered for data produced by a filter (or predictor), ZLibOption.strategyHuffmanOnly to force Huffman encoding only (no string match), or ZLibOption.strategyRle to limit match distances to one (run-length encoding).
final int windowBitsBase two logarithm of the window size (the size of the history buffer). It should be in the range 8..15. Larger values result in better compression at the expense of memory usage. The default value is 15
final List<int>? dictionaryInitial compression dictionary.
It should consist of strings (byte sequences) that are likely to be encountered later in the data to be compressed, with the most commonly used strings preferably put towards the end of the dictionary. Using a dictionary is most useful when the data to be compressed is short and can be predicted with good accuracy; the data can then be compressed better than with the default empty dictionary.
final bool rawWhen true, deflate generates raw data with no zlib header or trailer, and will not compute an adler32 check value
Methods
List<int> convert(List<int> bytes)Convert a list of bytes using the options given to the ZLibEncoder constructor.
import 'raya:io';
void main() {
final input = List.filled(4096, 65);
final out = ZLibEncoder(level: 9).convert(input);
print('4096 identical bytes compress to ${out.length < 50 ? 'under 50' : out.length} bytes');
print('decodes back: ${zlib.decode(out).length}');
}4096 identical bytes compress to under 50 bytes decodes back: 4096
ByteConversionSink startChunkedConversion(Sink<List<int>> sink)Start a chunked conversion using the options given to the ZLibEncoder constructor.
Accepts any Sink<List<int>>, but prefers a ByteConversionSink, and converts any other sink to a ByteConversionSink before using it.
import 'raya:io';
import 'raya:convert';
void main() {
final out = ByteConversionSink.withCallback((bytes) => print('decoded: ${utf8.decode(zlib.decode(bytes))}'));
final sink = ZLibEncoder().startChunkedConversion(out);
sink.add(utf8.encode('stream '));
sink.add(utf8.encode('of chunks'));
sink.close();
}decoded: stream of chunks
ZLibDecoder
final class ZLibDecoder extends Converter<List<int>, List<int>>
The ZLibDecoder is used by ZLibCodec and GZipCodec to decompress data.
Constructors
ZLibDecoder({this.gzip = false, this.windowBits = ZLibOption.defaultWindowBits, this.dictionary, this.raw = false})import 'raya:io';
import 'raya:convert';
void main() {
final gz = gzip.encode(utf8.encode('compressed with gzip'));
print(utf8.decode(ZLibDecoder(gzip: true).convert(gz)));
final raw = ZLibEncoder(raw: true).convert(utf8.encode('raw deflate'));
print(utf8.decode(ZLibDecoder(raw: true).convert(raw)));
}compressed with gzip raw deflate
Properties
final bool gzipWhen true, all concatenated compressed data sets in the input are decompressed and concatenated in the output.
final int windowBitsBase two logarithm of the window size (the size of the history buffer). It should be in the range 8..15. Larger values result in better compression at the expense of memory usage. The default value is 15.
final List<int>? dictionaryInitial compression dictionary.
It should consist of strings (byte sequences) that are likely to be encountered later in the data to be compressed, with the most commonly used strings preferably put towards the end of the dictionary. Using a dictionary is most useful when the data to be compressed is short and can be predicted with good accuracy; the data can then be compressed better than with the default empty dictionary.
final bool rawWhen true, deflate generates raw data with no zlib header or trailer, and will not compute an adler32 check value
Methods
List<int> convert(List<int> bytes)Convert a list of bytes using the options given to the ZLibDecoder constructor.
import 'raya:io';
import 'raya:convert';
void main() {
final packed = zlib.encode(utf8.encode('Raya ' * 3));
print('unpacked: ${utf8.decode(zlib.decoder.convert(packed))}');
try {
zlib.decoder.convert([1, 2, 3]);
} on FormatException {
print('not zlib data: FormatException');
}
}unpacked: Raya Raya Raya not zlib data: FormatException
ByteConversionSink startChunkedConversion(Sink<List<int>> sink)Start a chunked conversion.
Accepts any Sink<List<int>>, but prefers a ByteConversionSink, and converts any other sink to a ByteConversionSink before using it.
import 'raya:io';
import 'raya:convert';
void main() {
final packed = zlib.encode(utf8.encode('split across two chunks'));
final out = ByteConversionSink.withCallback((b) => print('decoded: ${utf8.decode(b)}'));
final sink = zlib.decoder.startChunkedConversion(out);
final mid = packed.length ~/ 2;
sink.add(packed.sublist(0, mid));
sink.add(packed.sublist(mid));
sink.close();
}decoded: split across two chunks
RawZLibFilter
abstract interface class RawZLibFilter
The RawZLibFilter class provides a low-level interface to zlib.
Constructors
factory RawZLibFilter.deflateFilter({bool gzip = false, int level = ZLibOption.defaultLevel, int windowBits = ZLibOption.defaultWindowBits, int memLevel = ZLibOption.defaultMemLevel, int strategy = ZLibOption.strategyDefault, List<int>? dictionary, bool raw = false})Returns a RawZLibFilter whose process and processed methods compress data.
import 'raya:io';
import 'raya:convert';
void main() {
final f = RawZLibFilter.deflateFilter(level: 9);
final input = utf8.encode('abcabcabcabcabcabc');
f.process(input, 0, input.length);
final out = <int>[];
for (List<int>? c; (c = f.processed(end: true)) != null;) out.addAll(c!);
print('deflated ${input.length} -> ${out.length} bytes; inflates to ${utf8.decode(zlib.decode(out))}');
}deflated 18 -> 13 bytes; inflates to abcabcabcabcabcabc
factory RawZLibFilter.inflateFilter({bool gzip = false, int windowBits = ZLibOption.defaultWindowBits, List<int>? dictionary, bool raw = false})Returns a RawZLibFilter whose process and processed methods decompress data.
import 'raya:io';
import 'raya:convert';
void main() {
final packed = zlib.encode(utf8.encode('filter me'));
final f = RawZLibFilter.inflateFilter();
f.process(packed, 0, packed.length);
final out = <int>[];
for (List<int>? c; (c = f.processed()) != null;) out.addAll(c!);
print('inflated: ${utf8.decode(out)}');
}inflated: filter me
Methods
void process(List<int> data, int start, int end)Process a chunk of data.
This method must only be called when processed returns null.
import 'raya:io';
import 'raya:convert';
void main() {
final f = RawZLibFilter.deflateFilter();
final data = utf8.encode('xxhello worldxx');
f.process(data, 2, 13); // only "hello world"
final out = <int>[];
for (List<int>? c; (c = f.processed(end: true)) != null;) out.addAll(c!);
print('compressed slice decodes to: ${utf8.decode(zlib.decode(out))}');
}compressed slice decodes to: hello world
List<int>? processed({bool flush = true, bool end = false})Get a chunk of processed data.
When there are no more data available, processed will return null. Set flush to false for non-final calls to improve performance of some filters.
The last call to processed should have end set to true. This will make sure an 'end' packet is written on the stream.
import 'raya:io';
void main() {
final f = RawZLibFilter.deflateFilter();
final out = <int>[];
// Even before any input the filter can hand out the 2-byte zlib header.
final header = f.processed(flush: false)!;
print('header: $header');
out.addAll(header);
f.process(List.filled(100, 7), 0, 100);
// Call until it returns null; end: true finishes the stream.
for (List<int>? c; (c = f.processed(end: true)) != null;) out.addAll(c!);
print('compressed to ${out.length} bytes; inflates to ${zlib.decode(out).length} bytes');
}header: [120, 156] compressed to 12 bytes; inflates to 100 bytes
Directory
abstract interface class Directory implements FileSystemEntity
A reference to a directory (or folder) on the file system.
A Directory is an object holding a path on which operations can be performed. The path to the directory can be absolute or relative. It allows access to the parent directory, since it is a FileSystemEntity.
The Directory also provides static access to the system's temporary file directory, systemTemp, and the ability to access and change the current directory.
Create a new Directory to give access the directory with the specified path:
var myDir = Directory('myDir');
Most instance methods of Directory exist in both synchronous and asynchronous variants, for example, create and createSync. Unless you have a specific reason for using the synchronous version of a method, prefer the asynchronous version to avoid blocking your program.
Create a directory
The following code sample creates a directory using the create method. By setting the recursive parameter to true, you can create the named directory and all its necessary parent directories, if they do not already exist.
import 'raya:io';
void main() async {
// Creates dir/ and dir/subdir/.
var directory = await Directory('dir/subdir').create(recursive: true);
print(directory.path);
}
List the entries of a directory
Use the list or listSync methods to get the files and directories contained in a directory. Set recursive to true to recursively list all subdirectories. Set followLinks to true to follow symbolic links. The list method returns a Stream of FileSystemEntity objects. Listen on the stream to access each object as it is found:
import 'raya:io';
void main() async {
// Get the system temp directory.
var systemTempDir = Directory.systemTemp;
// List directory contents, recursing into sub-directories,
// but not following symbolic links.
await for (var entity in
systemTempDir.list(recursive: true, followLinks: false)) {
print(entity.path);
}
}
The use of asynchronous methods
I/O operations can block a program for some period of time while it waits for the operation to complete. To avoid this, all methods involving I/O have an asynchronous variant which returns a Future. This future completes when the I/O operation finishes. While the I/O operation is in progress, the Raya program is not blocked, and can perform other operations.
For example, the exists method, which determines whether the directory exists, returns a boolean value asynchronously using a Future.
import 'raya:io';
void main() async {
final myDir = Directory('dir');
var isThere = await myDir.exists();
print(isThere ? 'exists' : 'nonexistent');
}
In addition to exists, the stat, rename, and other methods are also asynchronous.
Constructors
factory Directory(String path)Creates a Directory object.
If path is a relative path, it will be interpreted relative to the current working directory (see Directory.current), when used.
If path is an absolute path, it will be immune to changes to the current working directory.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final dir = Directory('${tmp.path}/photos');
print('exists: ${dir.existsSync()}');
dir.createSync();
print('exists after create: ${dir.existsSync()}');
print('absolute: ${dir.isAbsolute}');
tmp.deleteSync(recursive: true);
}exists: false exists after create: true absolute: true
factory Directory.fromRawPath(Uint8List path)import 'raya:io';
import 'raya:convert';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final dir = Directory.fromRawPath(utf8.encode('${tmp.path}/résumés'))..createSync();
print('name: ${dir.path.split('/').last}');
print('exists: ${dir.existsSync()}');
tmp.deleteSync(recursive: true);
}name: résumés exists: true
factory Directory.fromUri(Uri uri)Create a Directory from a URI.
If uri cannot reference a directory this throws UnsupportedError.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final dir = Directory.fromUri(tmp.uri.resolve('my%20dir/'))..createSync();
print('name: ${dir.path.split('/').where((s) => s.isNotEmpty).last}');
print('uri ends with slash: ${dir.uri.path.endsWith('/')}');
tmp.deleteSync(recursive: true);
}name: my dir uri ends with slash: true
Static
static Directory get currentCreates a directory object pointing to the current working directory.
static void set current(dynamic path)Sets the current working directory of the Raya process.
This affects all running isolates. The new value set can be either a Directory or a String.
The new value is passed to the OS's system call unchanged, so a relative path passed as the new working directory will be resolved by the OS.
Note that setting the current working directory is a synchronous operation and that it changes the working directory of all isolates.
Use this with care — especially when working with asynchronous operations and multiple isolates. Changing the working directory, while asynchronous operations are pending or when other isolates are working with the file system, can lead to unexpected results.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final before = Directory.current;
Directory.current = tmp;
File('relative.txt').writeAsStringSync('written relative to current');
Directory.current = before;
print('back to start: ${Directory.current.path == before.path}');
print('file landed in tmp: ${File('${tmp.path}/relative.txt').existsSync()}');
tmp.deleteSync(recursive: true);
}back to start: true file landed in tmp: true
static Directory get systemTempThe system temp directory.
This is the directory provided by the operating system for creating temporary files and directories in. The location of the system temporary directory is platform-dependent, and may be controlled by an environment variable on some platforms.
Properties
Uri get uriDirectory get absoluteMethods
Future<Directory> create({bool recursive = false})Creates the directory if it doesn't exist.
If recursive is false, only the last directory in the path is created. If recursive is true, all non-existing path components are created. If the directory already exists nothing is done.
Returns a Future<Directory> that completes with this directory once it has been created. If the directory cannot be created the future completes with an exception.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final deep = Directory('${tmp.path}/a/b/c');
try {
await deep.create();
} on FileSystemException {
print('create without recursive: fails (parent missing)');
}
await deep.create(recursive: true);
print('create recursive: ${await deep.exists()}');
await tmp.delete(recursive: true);
}create without recursive: fails (parent missing) create recursive: true
void createSync({bool recursive = false})Synchronously creates the directory if it doesn't exist.
If recursive is false, only the last directory in the path is created. If recursive is true, all non-existing path components are created. If the directory already exists nothing is done.
If the directory cannot be created an exception is thrown.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
for (final p in ['src/lib', 'src/test', 'docs']) {
Directory('${tmp.path}/$p').createSync(recursive: true);
}
Directory('${tmp.path}/docs').createSync(); // already there: no error
final tree = tmp.listSync(recursive: true).map((e) => e.path.substring(tmp.path.length + 1)).toList()..sort();
print('tree: $tree');
tmp.deleteSync(recursive: true);
}tree: [docs, src, src/lib, src/test]
Future<Directory> createTemp([String? prefix])Creates a temporary directory in this directory.
Additional random characters are appended to prefix to produce a unique directory name. If prefix is missing or null, the empty string is used as prefix.
Returns a Future<Directory> that completes with the newly created temporary directory.
import 'raya:io';
Future<void> main() async {
final work = await Directory.systemTemp.createTemp('job_');
final name = work.path.split('/').last;
print('prefix kept: ${name.startsWith('job_')}');
print('unique suffix added: ${name.length > 'job_'.length}');
await File('${work.path}/out.txt').writeAsString('ok');
await work.delete(recursive: true);
print('cleaned up: ${!await work.exists()}');
}prefix kept: true unique suffix added: true cleaned up: true
Directory createTempSync([String? prefix])Synchronously creates a temporary directory in this directory.
Additional random characters are appended to prefix to produce a unique directory name. If prefix is missing or null, the empty string is used as prefix.
Returns the newly created temporary directory.
import 'raya:io';
void main() {
final a = Directory.systemTemp.createTempSync('raya_ex_');
final b = Directory.systemTemp.createTempSync('raya_ex_');
print('two temp dirs differ: ${a.path != b.path}');
final nested = a.createTempSync('inner');
print('nested inside a: ${nested.parent.path == a.path}');
a.deleteSync(recursive: true);
b.deleteSync(recursive: true);
}two temp dirs differ: true nested inside a: true
Future<String> resolveSymbolicLinks()import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final root = tmp.resolveSymbolicLinksSync();
Directory('$root/real').createSync();
Link('$root/alias').createSync('$root/real');
final resolved = await Directory('$root/alias').resolveSymbolicLinks();
print('alias resolves to: ${resolved.substring(root.length + 1)}');
final dotted = await Directory('$root/real/../real').resolveSymbolicLinks();
print('.. removed: ${dotted.substring(root.length + 1)}');
await tmp.delete(recursive: true);
}alias resolves to: real .. removed: real
String resolveSymbolicLinksSync()import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final root = tmp.resolveSymbolicLinksSync();
Directory('$root/v2/assets').createSync(recursive: true);
Link('$root/current').createSync('v2');
final p = Directory('$root/current/assets').resolveSymbolicLinksSync();
print('current/assets -> ${p.substring(root.length + 1)}');
tmp.deleteSync(recursive: true);
}current/assets -> v2/assets
Future<Directory> rename(String newPath)Renames this directory.
Returns a Future<Directory> that completes with a Directory for the renamed directory.
If newPath identifies an existing directory, then the behavior is platform-specific. On all platforms, the future completes with a FileSystemException if the existing directory is not empty. On POSIX systems, if newPath identifies an existing empty directory then that directory is deleted before this directory is renamed.
If newPath identifies an existing file or link, the operation fails and the future completes with a FileSystemException.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final draft = Directory('${tmp.path}/draft')..createSync();
File('${draft.path}/page.txt').writeAsStringSync('p1');
final published = await draft.rename('${tmp.path}/published');
print('draft exists: ${await draft.exists()}');
print('published file: ${File('${published.path}/page.txt').readAsStringSync()}');
await tmp.delete(recursive: true);
}draft exists: false published file: p1
Directory renameSync(String newPath)Synchronously renames this directory.
Returns a Directory for the renamed directory.
If newPath identifies an existing directory, then the behavior is platform-specific. On all platforms, a FileSystemException is thrown if the existing directory is not empty. On POSIX systems, if newPath identifies an existing empty directory then that directory is deleted before this directory is renamed.
If newPath identifies an existing file or link the operation fails and a FileSystemException is thrown.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final a = Directory('${tmp.path}/a')..createSync();
final b = a.renameSync('${tmp.path}/b');
final names = tmp.listSync().map((e) => e.path.split('/').last).toList();
print('after rename: $names');
print('returned dir name: ${b.path.split('/').last}');
tmp.deleteSync(recursive: true);
}after rename: [b] returned dir name: b
Future<FileSystemEntity> delete({bool recursive = false})Deletes this Directory.
If recursive is false:
- If
pathcorresponds to an empty directory, then that directory is deleted. Ifpathcorresponds to a link, and that link resolves to a directory, then the link atpathwill be deleted. In all other cases,deletecompletes with aFileSystemException.
If recursive is true:
- The
FileSystemEntityatpathis deleted regardless of type. Ifpathcorresponds to a file or link, then that file or link is deleted. Ifpathcorresponds to a directory, then it and all sub-directories and files in those directories are deleted. Links are not followed when deleting recursively. Only the link is deleted, not its target. This behavior allowsdeleteto be used to unconditionally delete any file system object.
If this Directory cannot be deleted, then delete completes with a FileSystemException.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final dir = Directory('${tmp.path}/cache')..createSync();
File('${dir.path}/x').writeAsStringSync('x');
try {
await dir.delete();
} on FileSystemException {
print('non-empty, not recursive: fails');
}
await dir.delete(recursive: true);
print('recursive delete: exists=${await dir.exists()}');
await tmp.delete(recursive: true);
}non-empty, not recursive: fails recursive delete: exists=false
void deleteSync({bool recursive = false})Synchronously deletes this Directory.
If recursive is false:
- If
pathcorresponds to an empty directory, then that directory is deleted. Ifpathcorresponds to a link, and that link resolves to a directory, then the link atpathwill be deleted. In all other cases,deletethrows aFileSystemException.
If recursive is true:
- The
FileSystemEntityatpathis deleted regardless of type. Ifpathcorresponds to a file or link, then that file or link is deleted. Ifpathcorresponds to a directory, then it and all sub-directories and files in those directories are deleted. Links are not followed when deleting recursively. Only the link is deleted, not its target. This behavior allowsdeleteto be used to unconditionally delete any file system object.
If this Directory cannot be deleted, then delete throws a FileSystemException.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final empty = Directory('${tmp.path}/empty')..createSync();
empty.deleteSync();
print('empty dir deleted: ${!empty.existsSync()}');
tmp.deleteSync(recursive: true);
print('temp tree deleted: ${!tmp.existsSync()}');
}empty dir deleted: true temp tree deleted: true
Stream<FileSystemEntity> list({bool recursive = false, bool followLinks = true})Lists the sub-directories and files of this Directory.
Optionally recurses into sub-directories.
If followLinks is false, then any symbolic links found are reported as Link objects, rather than as directories or files, and are not recursed into.
If followLinks is true, then working links are reported as directories or files, depending on what they point to, and links to directories are recursed into if recursive is true.
Broken links are reported as Link objects.
If a symbolic link makes a loop in the file system, then a recursive listing will not follow a link twice in the same recursive descent, but will report it as a Link the second time it is seen.
The result is a Stream of FileSystemEntity objects for the directories, files, and links. The Stream will be in an arbitrary order and does not include the special entries '.' and '..'.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
File('${tmp.path}/a.txt').writeAsStringSync('a');
Directory('${tmp.path}/sub').createSync();
File('${tmp.path}/sub/b.txt').writeAsStringSync('b');
final top = <String>[], all = <String>[];
await for (final e in tmp.list()) {
top.add('${e.path.substring(tmp.path.length + 1)} (${e is Directory ? 'dir' : 'file'})');
}
await for (final e in tmp.list(recursive: true)) {
all.add(e.path.substring(tmp.path.length + 1));
}
print('top level: ${top..sort()}');
print('recursive: ${all..sort()}');
await tmp.delete(recursive: true);
}top level: [a.txt (file), sub (dir)] recursive: [a.txt, sub, sub/b.txt]
List<FileSystemEntity> listSync({bool recursive = false, bool followLinks = true})Lists the sub-directories and files of this Directory. Optionally recurses into sub-directories.
If followLinks is false, then any symbolic links found are reported as Link objects, rather than as directories or files, and are not recursed into.
If followLinks is true, then working links are reported as directories or files, depending on what they point to, and links to directories are recursed into if recursive is true.
Broken links are reported as Link objects.
If a link makes a loop in the file system, then a recursive listing will not follow a link twice in the same recursive descent, but will report it as a Link the second time it is seen.
Returns a List containing FileSystemEntity objects for the directories, files, and links. The List will be in an arbitrary order and does not include the special entries '.' and '..'.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
for (final n in ['b.ray', 'a.ray', 'notes.md']) {
File('${tmp.path}/$n').writeAsStringSync(n);
}
final sources = tmp
.listSync()
.whereType<File>()
.map((f) => f.path.split('/').last)
.where((n) => n.endsWith('.ray'))
.toList()
..sort();
print('.ray files: $sources');
tmp.deleteSync(recursive: true);
}.ray files: [a.ray, b.ray]
String toString()Returns a human readable representation of this Directory.
import 'raya:io';
void main() {
final dir = Directory('/data/projects');
print('toString: $dir');
print('path: ${dir.path}');
print('file: ${File('notes.txt')}');
print('link: ${Link('latest')}');
}toString: Directory: '/data/projects' path: /data/projects file: File: 'notes.txt' link: Link: 'latest'
FileMode
class FileMode
The modes in which a File can be opened.
Static
static const write = FileMode._internal(1)Mode for opening a file for reading and writing. The file is overwritten if it already exists. The file is created if it does not already exist.
static const append = FileMode._internal(2)Mode for opening a file for reading and writing to the end of it. The file is created if it does not already exist.
static const writeOnly = FileMode._internal(3)Mode for opening a file for writing only. The file is overwritten if it already exists. The file is created if it does not already exist.
static const writeOnlyAppend = FileMode._internal(4)Mode for opening a file for writing only to the end of it. The file is created if it does not already exist.
FileLock
class FileLock
Type of lock when requesting a lock on a file.
Static
static const blockingExclusive = FileLock._internal(4)Blocking exclusive file lock.
File
abstract interface class File implements FileSystemEntity
A reference to a file on the file system.
A File holds a path on which operations can be performed. You can get the parent directory of the file using parent, a property inherited from FileSystemEntity.
Create a new File object with a pathname to access the specified file on the file system from your program.
var myFile = File('file.txt');
The File class contains methods for manipulating files and their contents. Using methods in this class, you can open and close files, read to and write from them, create and delete them, and check for their existence.
When reading or writing a file, you can use streams (with openRead), random access operations (with open), or convenience methods such as readAsString,
Most methods in this class occur in synchronous and asynchronous pairs, for example, readAsString and readAsStringSync. Unless you have a specific reason for using the synchronous version of a method, prefer the asynchronous version to avoid blocking your program.
If path is a link
If path is a symbolic link, rather than a file, then the methods of File operate on the ultimate target of the link, except for delete and deleteSync, which operate on the link.
Read from a file
The following code sample reads the entire contents from a file as a string using the asynchronous readAsString method:
import 'raya:async';
import 'raya:io';
void main() {
File('file.txt').readAsString().then((String contents) {
print(contents);
});
}
A more flexible and useful way to read a file is with a Stream. Open the file with openRead, which returns a stream that provides the data in the file as chunks of bytes. Read the stream to process the file contents when available. You can use various transformers in succession to manipulate the file content into the required format, or to prepare it for output.
You might want to use a stream to read large files, to manipulate the data with transformers, or for compatibility with another API, such as WebSockets.
import 'raya:io';
import 'raya:convert';
import 'raya:async';
void main() async {
final file = File('file.txt');
Stream<String> lines = file.openRead()
.transform(utf8.decoder) // Decode bytes to UTF-8.
.transform(LineSplitter()); // Convert stream to individual lines.
try {
await for (var line in lines) {
print('$line: ${line.length} characters');
}
print('File is now closed.');
} catch (e) {
print('Error: $e');
}
}
Write to a file
To write a string to a file, use the writeAsString method:
import 'raya:io';
void main() async {
final filename = 'file.txt';
var file = await File(filename).writeAsString('some content');
// Do something with the file.
}
You can also write to a file using a Stream. Open the file with openWrite, which returns an IOSink to which you can write data. Be sure to close the sink with the IOSink.close method.
import 'raya:io';
void main() async {
var file = File('file.txt');
var sink = file.openWrite();
sink.write('FILE ACCESSED ${DateTime.now()}\n');
await sink.flush();
// Close the IOSink to free system resources.
await sink.close();
}
The use of asynchronous methods
To avoid unintentional blocking of the program, several methods are asynchronous and return a Future. For example, the length method, which gets the length of a file, returns a Future. Wait for the future to get the result when it's ready.
import 'raya:io';
void main() async {
final file = File('file.txt');
var length = await file.length();
print(length);
}
In addition to length, the exists, lastModified, stat, and other methods, are asynchronous.
Special 'nul' file
On Linux and Mac '/dev/null' and on Windows '\\?\NUL' refer to a special file, such that all writes to it get consumed and disappear, and all reads produce empty output. Note that on Windows 'nul'(without '\\?\'-prefix) refers to a regular file named 'nul' in current directory.
Constructors
factory File(String path)Creates a File object.
If path is a relative path, it will be interpreted relative to the current working directory (see Directory.current), when used.
If path is an absolute path, it will be immune to changes to the current working directory.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final file = File('${tmp.path}/notes.txt');
print('exists before write: ${file.existsSync()}');
file.writeAsStringSync('hello');
print('exists after write: ${file.existsSync()}');
print('name: ${file.uri.pathSegments.last}');
print('parent is tmp: ${file.parent.path == tmp.path}');
tmp.deleteSync(recursive: true);
}exists before write: false exists after write: true name: notes.txt parent is tmp: true
factory File.fromUri(Uri uri)Create a File object from a URI.
If uri cannot reference a file this throws UnsupportedError.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final uri = tmp.uri.resolve('data%20file.txt');
final file = File.fromUri(uri);
file.writeAsStringSync('from a uri');
print('uri segment: ${uri.pathSegments.last}');
print('file name: ${file.path.split('/').last}');
print('contents: ${file.readAsStringSync()}');
tmp.deleteSync(recursive: true);
}uri segment: data file.txt file name: data file.txt contents: from a uri
factory File.fromRawPath(Uint8List rawPath)Creates a File object from a raw path.
A raw path is a sequence of bytes, as paths are represented by the OS.
import 'raya:io';
import 'raya:convert';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final raw = utf8.encode('${tmp.path}/café.txt');
final file = File.fromRawPath(raw);
file.writeAsStringSync('raw bytes path');
print('name: ${file.path.split('/').last}');
print('read: ${file.readAsStringSync()}');
tmp.deleteSync(recursive: true);
}name: café.txt read: raw bytes path
Properties
File get absoluteMethods
Future<File> create({bool recursive = false, bool exclusive = false})Creates the file.
Returns a Future<File> that completes with the file when it has been created.
If recursive is false, the default, the file is created only if all directories in its path already exist. If recursive is true, any non-existing parent paths are created first.
If exclusive is true and to-be-created file already exists, this operation completes the future with a PathExistsException.
If exclusive is false, existing files are left untouched by create. Calling create on an existing file still might fail if there are restrictive permissions on the file.
Completes the future with a FileSystemException if the operation fails.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final file = File('${tmp.path}/a/b/c.txt');
try {
await file.create();
} on FileSystemException catch (e) {
print('without recursive: ${e.runtimeType}');
}
await file.create(recursive: true);
print('with recursive: ${await file.exists()}');
print('empty length: ${await file.length()}');
await tmp.delete(recursive: true);
}without recursive: PathNotFoundException with recursive: true empty length: 0
void createSync({bool recursive = false, bool exclusive = false})Synchronously creates the file.
If recursive is false, the default, the file is created only if all directories in its path already exist. If recursive is true, all non-existing parent paths are created first.
If exclusive is true and to-be-created file already exists, then a FileSystemException is thrown.
If exclusive is false, existing files are left untouched by createSync. Calling createSync on an existing file still might fail if there are restrictive permissions on the file.
Throws a FileSystemException if the operation fails.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final file = File('${tmp.path}/logs/today.log')..createSync(recursive: true);
print('created: ${file.existsSync()}, length ${file.lengthSync()}');
file.writeAsStringSync('line 1\n');
file.createSync(); // already exists: leaves contents alone
print('after second create: ${file.readAsStringSync().trim()}');
try {
file.createSync(exclusive: true);
} on FileSystemException {
print('exclusive create fails when the file exists');
}
tmp.deleteSync(recursive: true);
}created: true, length 0 after second create: line 1 exclusive create fails when the file exists
Future<File> rename(String newPath)Renames this file.
Returns a Future<File> that completes with a File for the renamed file.
If newPath is a relative path, it is resolved against the current working directory (Directory.current). This means that simply changing the name of a file, but keeping it the original directory, requires creating a new complete path with the new name at the end. Example:
Future<File> changeFileNameOnly(File file, String newFileName) {
var path = file.path;
var lastSeparator = path.lastIndexOf(Platform.pathSeparator);
var newPath = path.substring(0, lastSeparator + 1) + newFileName;
return file.rename(newPath);
}
On some platforms, a rename operation cannot move a file between different file systems. If that is the case, instead copy the file to the new location and then remove the original.
If newPath identifies an existing file or link, that entity is removed first. If newPath identifies an existing directory, the operation fails and the future completes with a FileSystemException.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final draft = File('${tmp.path}/draft.txt')..writeAsStringSync('v1');
final done = await draft.rename('${tmp.path}/final.txt');
print('old exists: ${await draft.exists()}');
print('new exists: ${await done.exists()}');
print('new name: ${done.path.split('/').last}, contents ${await done.readAsString()}');
await tmp.delete(recursive: true);
}old exists: false new exists: true new name: final.txt, contents v1
File renameSync(String newPath)Synchronously renames this file.
Returns a File for the renamed file.
If newPath is a relative path, it is resolved against the current working directory (Directory.current). This means that simply changing the name of a file, but keeping it the original directory, requires creating a new complete path with the new name at the end. Example:
File changeFileNameOnlySync(File file, String newFileName) {
var path = file.path;
var lastSeparator = path.lastIndexOf(Platform.pathSeparator);
var newPath = path.substring(0, lastSeparator + 1) + newFileName;
return file.renameSync(newPath);
}
On some platforms, a rename operation cannot move a file between different file systems. If that is the case, instead copySync the file to the new location and then deleteSync the original.
If newPath identifies an existing file or link, that entity is removed first. If newPath identifies an existing directory the operation throws a FileSystemException.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final a = File('${tmp.path}/a.txt')..writeAsStringSync('A');
final b = File('${tmp.path}/b.txt')..writeAsStringSync('B');
// Renaming onto an existing file replaces it.
a.renameSync(b.path);
print('a exists: ${a.existsSync()}');
print('b holds: ${b.readAsStringSync()}');
tmp.deleteSync(recursive: true);
}a exists: false b holds: A
Future<FileSystemEntity> delete({bool recursive = false})Deletes this File.
If recursive is false:
- If
pathcorresponds to a regular file, named pipe or socket, then that path is deleted. Ifpathcorresponds to a link, and that link resolves to a file, then the link atpathwill be deleted. In all other cases,deletecompletes with aFileSystemException.
If recursive is true:
- The
FileSystemEntityatpathis deleted regardless of type. Ifpathcorresponds to a file or link, then that file or link is deleted. Ifpathcorresponds to a directory, then it and all sub-directories and files in those directories are deleted. Links are not followed when deleting recursively. Only the link is deleted, not its target. This behavior allowsdeleteto be used to unconditionally delete any file system object.
If this File cannot be deleted, then delete completes with a FileSystemException.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final file = File('${tmp.path}/temp.bin')..writeAsBytesSync([1, 2, 3]);
print('before: ${await file.exists()}');
await file.delete();
print('after: ${await file.exists()}');
try {
await file.delete();
} on PathNotFoundException {
print('deleting again: PathNotFoundException');
}
await tmp.delete(recursive: true);
}before: true after: false deleting again: PathNotFoundException
void deleteSync({bool recursive = false})Synchronously deletes this File.
If recursive is false:
- If
pathcorresponds to a regular file, named pipe or socket, then that path is deleted. Ifpathcorresponds to a link, and that link resolves to a file, then the link atpathwill be deleted. In all other cases,deletethrows aFileSystemException.
If recursive is true:
- The
FileSystemEntityatpathis deleted regardless of type. Ifpathcorresponds to a file or link, then that file or link is deleted. Ifpathcorresponds to a directory, then it and all sub-directories and files in those directories are deleted. Links are not followed when deleting recursively. Only the link is deleted, not its target. This behavior allowsdeleteto be used to unconditionally delete any file system object.
If this File cannot be deleted, then delete throws a FileSystemException.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
for (final n in ['a', 'b', 'c']) {
File('${tmp.path}/$n.tmp').writeAsStringSync(n);
}
File('${tmp.path}/b.tmp').deleteSync();
final left = tmp.listSync().map((e) => e.path.split('/').last).toList()..sort();
print('left after deleting b.tmp: $left');
tmp.deleteSync(recursive: true);
}left after deleting b.tmp: [a.tmp, c.tmp]
Future<File> copy(String newPath)Copies this file.
If newPath is a relative path, it is resolved against the current working directory (Directory.current).
Returns a Future<File> that completes with a File for the copied file.
If newPath identifies an existing file, that file is removed first. If newPath identifies an existing directory, the operation fails and the future completes with an exception.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final src = File('${tmp.path}/src.txt')..writeAsStringSync('original');
final dst = await src.copy('${tmp.path}/dst.txt');
await dst.writeAsString(' + edited', mode: FileMode.append);
print('src: ${await src.readAsString()}');
print('dst: ${await dst.readAsString()}');
await tmp.delete(recursive: true);
}src: original dst: original + edited
File copySync(String newPath)Synchronously copies this file.
If newPath is a relative path, it is resolved against the current working directory (Directory.current).
Returns a File for the copied file.
If newPath identifies an existing file, that file is removed first. If newPath identifies an existing directory the operation fails and an exception is thrown.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final src = File('${tmp.path}/config.json')..writeAsStringSync('{"debug": false}');
final backup = src.copySync('${tmp.path}/config.json.bak');
src.writeAsStringSync('{"debug": true}');
print('current: ${src.readAsStringSync()}');
print('backup: ${backup.readAsStringSync()}');
tmp.deleteSync(recursive: true);
}current: {"debug": true}
backup: {"debug": false}Future<int> length()The length of the file.
Returns a Future<int> that completes with the length in bytes.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final file = File('${tmp.path}/x.txt');
await file.writeAsString('abc');
print('ascii "abc": ${await file.length()} bytes');
await file.writeAsString('ééé');
print('utf-8 "ééé": ${await file.length()} bytes');
await tmp.delete(recursive: true);
}ascii "abc": 3 bytes utf-8 "ééé": 6 bytes
int lengthSync()The length of the file provided synchronously.
Throws a FileSystemException if the operation fails.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final file = File('${tmp.path}/grow.bin')..writeAsBytesSync([]);
for (var i = 1; i <= 3; i++) {
file.writeAsBytesSync(List.filled(100, i), mode: FileMode.append);
print('after append $i: ${file.lengthSync()} bytes');
}
tmp.deleteSync(recursive: true);
}after append 1: 100 bytes after append 2: 200 bytes after append 3: 300 bytes
Future<DateTime> lastAccessed()The last-accessed time of the file.
Returns a Future<DateTime> that completes with the date and time when the file was last accessed, if the information is available.
Throws a FileSystemException if the operation fails.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final file = File('${tmp.path}/a.txt')..writeAsStringSync('x');
await file.setLastAccessed(DateTime.utc(2024, 1, 2, 3, 4, 5));
final t = (await file.lastAccessed()).toUtc();
print('last accessed: ${t.toIso8601String()}');
await tmp.delete(recursive: true);
}last accessed: 2024-01-02T03:04:05.000Z
DateTime lastAccessedSync()The last-accessed time of the file.
Returns the date and time when the file was last accessed, if the information is available. Blocks until the information can be returned or it is determined that the information is not available.
Throws a FileSystemException if the operation fails.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final file = File('${tmp.path}/a.txt')..writeAsStringSync('x');
file.setLastAccessedSync(DateTime.utc(2000, 1, 1));
print('year: ${file.lastAccessedSync().toUtc().year}');
print('is before 2001: ${file.lastAccessedSync().isBefore(DateTime.utc(2001))}');
tmp.deleteSync(recursive: true);
}year: 2000 is before 2001: true
Future setLastAccessed(DateTime time)Modifies the time the file was last accessed.
Returns a Future that completes once the operation has completed.
Throws a FileSystemException if the time cannot be set.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final file = File('${tmp.path}/a.txt')..writeAsStringSync('x');
final when = DateTime.utc(2023, 6, 15, 12);
await file.setLastAccessed(when);
print('set to: ${when.toIso8601String()}');
print('read back: ${(await file.lastAccessed()).toUtc().toIso8601String()}');
await tmp.delete(recursive: true);
}set to: 2023-06-15T12:00:00.000Z read back: 2023-06-15T12:00:00.000Z
void setLastAccessedSync(DateTime time)Synchronously modifies the time the file was last accessed.
Throws a FileSystemException if the time cannot be set.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final file = File('${tmp.path}/a.txt')..writeAsStringSync('x');
file.setLastAccessedSync(DateTime.utc(1999, 12, 31, 23, 59, 59));
print('accessed: ${file.lastAccessedSync().toUtc().toIso8601String()}');
tmp.deleteSync(recursive: true);
}accessed: 1999-12-31T23:59:59.000Z
Future<DateTime> lastModified()Get the last-modified time of the file.
Returns a Future<DateTime> that completes with the date and time when the file was last modified, if the information is available.
Throws a FileSystemException if the operation fails.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final file = File('${tmp.path}/report.txt')..writeAsStringSync('draft');
await file.setLastModified(DateTime.utc(2024, 3, 1, 9, 30));
final t = (await file.lastModified()).toUtc();
print('modified: ${t.toIso8601String()}');
print('weekday: ${t.weekday}');
await tmp.delete(recursive: true);
}modified: 2024-03-01T09:30:00.000Z weekday: 5
DateTime lastModifiedSync()Get the last-modified time of the file.
Returns the date and time when the file was last modified, if the information is available. Blocks until the information can be returned or it is determined that the information is not available.
Throws a FileSystemException if the operation fails.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final old = File('${tmp.path}/old.txt')..writeAsStringSync('o');
final fresh = File('${tmp.path}/new.txt')..writeAsStringSync('n');
old.setLastModifiedSync(DateTime.utc(2020));
fresh.setLastModifiedSync(DateTime.utc(2024));
final newer = old.lastModifiedSync().isAfter(fresh.lastModifiedSync()) ? old : fresh;
print('newer file: ${newer.path.split('/').last}');
tmp.deleteSync(recursive: true);
}newer file: new.txt
Future setLastModified(DateTime time)Modifies the time the file was last modified.
Returns a Future that completes once the operation has completed.
Throws a FileSystemException if the time cannot be set.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final file = File('${tmp.path}/a.txt')..writeAsStringSync('x');
await file.setLastModified(DateTime.utc(2010, 10, 10, 10, 10, 10));
print('modified: ${(await file.lastModified()).toUtc().toIso8601String()}');
await tmp.delete(recursive: true);
}modified: 2010-10-10T10:10:10.000Z
void setLastModifiedSync(DateTime time)Synchronously modifies the time the file was last modified.
If the attributes cannot be set, throws a FileSystemException.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final file = File('${tmp.path}/a.txt')..writeAsStringSync('x');
file.setLastModifiedSync(DateTime.utc(2022, 2, 22));
print('modified: ${file.lastModifiedSync().toUtc().toIso8601String()}');
print('stat agrees: ${file.statSync().modified == file.lastModifiedSync()}');
tmp.deleteSync(recursive: true);
}modified: 2022-02-22T00:00:00.000Z stat agrees: true
Future<RandomAccessFile> open({FileMode mode = FileMode.read})Opens the file for random access operations.
Returns a Future<RandomAccessFile> that completes with the opened random access file. RandomAccessFiles must be closed using the RandomAccessFile.close method.
Files can be opened in three modes:
FileMode.read: open the file for reading.
FileMode.write: open the file for both reading and writing and truncate the file to length zero. If the file does not exist the file is created.
FileMode.append: same asFileMode.writeexcept that the file is not truncated.
Throws a FileSystemException if the operation fails.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final file = File('${tmp.path}/data.bin');
final raf = await file.open(mode: FileMode.write);
await raf.writeFrom([10, 20, 30, 40]);
await raf.setPosition(1);
print('byte at 1: ${await raf.readByte()}');
await raf.close();
print('file bytes: ${file.readAsBytesSync()}');
await tmp.delete(recursive: true);
}byte at 1: 20 file bytes: [10, 20, 30, 40]
RandomAccessFile openSync({FileMode mode = FileMode.read})Synchronously opens the file for random access operations.
The result is a RandomAccessFile on which random access operations can be performed. Opened RandomAccessFiles must be closed using the RandomAccessFile.close method.
See open for information on the mode argument.
Throws a FileSystemException if the operation fails.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final file = File('${tmp.path}/data.txt')..writeAsStringSync('0123456789');
final raf = file.openSync(); // FileMode.read
raf.setPositionSync(4);
print('read 3 from 4: ${String.fromCharCodes(raf.readSync(3))}');
print('position now: ${raf.positionSync()}');
raf.closeSync();
tmp.deleteSync(recursive: true);
}read 3 from 4: 456 position now: 7
Stream<List<int>> openRead([int? start, int? end])Creates a new independent Stream for the contents of this file.
If start is present, the file will be read from byte-offset start. Otherwise from the beginning (index 0).
If end is present, only bytes up to byte-index end will be read. Otherwise, until end of file.
In order to make sure that system resources are freed, the stream must be read to completion or the subscription on the stream must be cancelled.
If File is a named pipe then the returned Stream will wait until the write side of the pipe is closed before signaling "done". If there are no writers attached to the pipe when it is opened, then Stream.listen will wait until a writer opens the pipe.
An error opening or reading the file will appear as a FileSystemException error event on the returned Stream, after which the Stream is closed. For example:
// This example will print the "Error reading file" message and the
// `await for` loop will complete normally, without seeing any data
// events.
final stream = File('does-not-exist')
.openRead()
.handleError((e) => print('Error reading file: $e'));
await for (final data in stream) {
print(data);
}import 'raya:io';
import 'raya:convert';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final file = File('${tmp.path}/lines.txt')..writeAsStringSync('alpha\nbeta\ngamma\n');
final lines = file.openRead().transform(utf8.decoder).transform(const LineSplitter());
await for (final line in lines) {
print('line: $line');
}
final middle = await file.openRead(6, 10).transform(utf8.decoder).join();
print('bytes 6..10: $middle');
await tmp.delete(recursive: true);
}line: alpha line: beta line: gamma bytes 6..10: beta
IOSink openWrite({FileMode mode = FileMode.write, Encoding encoding = utf8})Creates a new independent IOSink for the file.
The IOSink must be closed when no longer used, to free system resources.
An IOSink for a file can be opened in two modes:
FileMode.write: truncates the file to length zero.FileMode.append: sets the initial write position to the end of the file.
When writing strings through the returned IOSink the encoding specified using encoding will be used. The returned IOSink has an encoding property which can be changed after the IOSink has been created.
The returned IOSink does not transform newline characters ("\n") to the platform's conventional line ending (e.g. "\r\n" on Windows). Write a Platform.lineTerminator if a platform-specific line ending is needed.
If an error occurs while opening or writing to the file, the IOSink.done IOSink.flush, and IOSink.close futures will all complete with a FileSystemException. You must handle errors from the IOSink.done future or the error will be uncaught.
For example, FutureExtensions.ignore the IOSink.done error and remember to await the IOSink.flush and IOSink.close calls within a try/catch:
final sink = File('/tmp').openWrite(); // Can't write to /tmp
sink.done.ignore();
sink.write("This is a test");
try {
// If one of these isn't awaited, then errors will pass silently!
await sink.flush();
await sink.close();
} on FileSystemException catch (e) {
print('Error writing file: $e');
}
To handle errors asynchronously outside of the context of IOSink.flush and IOSink.close, you can Future.catchError the IOSink.done.
final sink = File('/tmp').openWrite(); // Can't write to /tmp
sink.done.catchError((e) {
// Handle the error.
});import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final file = File('${tmp.path}/out.csv');
final sink = file.openWrite();
sink.writeln('name,score');
for (final (n, s) in [('ada', 9), ('alan', 8)]) {
sink.writeln('$n,$s');
}
await sink.close();
final more = file.openWrite(mode: FileMode.append)..write('grace,10\n');
await more.close();
print(file.readAsStringSync().trim());
await tmp.delete(recursive: true);
}name,score ada,9 alan,8 grace,10
Future<Uint8List> readAsBytes()Reads the entire file contents as a list of bytes.
Returns a Future<Uint8List> that completes with the list of bytes that is the contents of the file.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final file = File('${tmp.path}/b.bin');
await file.writeAsBytes([0xCA, 0xFE, 0xBA, 0xBE]);
final bytes = await file.readAsBytes();
print('bytes: $bytes');
print('hex: ${bytes.map((b) => b.toRadixString(16)).join()}');
await tmp.delete(recursive: true);
}bytes: [202, 254, 186, 190] hex: cafebabe
Uint8List readAsBytesSync()Synchronously reads the entire file contents as a list of bytes.
Throws a FileSystemException if the operation fails.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final file = File('${tmp.path}/t.txt')..writeAsStringSync('Hié');
final bytes = file.readAsBytesSync();
print('bytes: $bytes');
print('type: ${bytes.runtimeType}');
tmp.deleteSync(recursive: true);
}bytes: [72, 105, 195, 169] type: Uint8List
Future<String> readAsString({Encoding encoding = utf8})Reads the entire file contents as a string using the given Encoding.
Returns a Future<String> that completes with the string once the file contents has been read.
import 'raya:io';
import 'raya:convert';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final file = File('${tmp.path}/t.txt');
await file.writeAsString('naïve café');
print('utf8: ${await file.readAsString()}');
print('latin1: ${await file.readAsString(encoding: latin1)}');
await tmp.delete(recursive: true);
}utf8: naïve café latin1: naïve café
String readAsStringSync({Encoding encoding = utf8})Synchronously reads the entire file contents as a string using the given Encoding.
Throws a FileSystemException if the operation fails.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final file = File('${tmp.path}/config.ini')..writeAsStringSync('[main]\nwidth=80\n');
final text = file.readAsStringSync();
print('chars: ${text.length}');
print('width: ${text.split('\n')[1].split('=')[1]}');
try {
File('${tmp.path}/missing.ini').readAsStringSync();
} on PathNotFoundException {
print('missing file: PathNotFoundException');
}
tmp.deleteSync(recursive: true);
}chars: 16 width: 80 missing file: PathNotFoundException
Future<List<String>> readAsLines({Encoding encoding = utf8})Reads the entire file contents as lines of text using the given Encoding.
Returns a Future<List<String>> that completes with the lines once the file contents has been read.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final file = File('${tmp.path}/todo.txt');
await file.writeAsString('buy milk\r\nwrite docs\nship it');
final lines = await file.readAsLines();
print('count: ${lines.length}');
for (final (i, l) in lines.indexed) {
print('${i + 1}. $l');
}
await tmp.delete(recursive: true);
}count: 3 1. buy milk 2. write docs 3. ship it
List<String> readAsLinesSync({Encoding encoding = utf8})Synchronously reads the entire file contents as lines of text using the given Encoding.
Throws a FileSystemException if the operation fails.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final file = File('${tmp.path}/nums.txt')..writeAsStringSync('3\n14\n15\n92\n');
final nums = file.readAsLinesSync().map(int.parse).toList();
print('lines: $nums');
print('sum: ${nums.reduce((a, b) => a + b)}');
tmp.deleteSync(recursive: true);
}lines: [3, 14, 15, 92] sum: 124
Future<File> writeAsBytes(List<int> bytes, {FileMode mode = FileMode.write, bool flush = false})Writes a list of bytes to a file.
Opens the file, writes the list of bytes to it, and closes the file. Returns a Future<File> that completes with this File object once the entire operation has completed.
By default writeAsBytes creates the file for writing and truncates the file if it already exists. In order to append the bytes to an existing file, pass FileMode.append as the optional mode parameter.
The elements of bytes should be integers in the range 0 to 255. Any integer, which is not in that range, is converted to a byte before being written. The conversion is equivalent to doing value.toUnsigned(8).
If the argument flush is set to true, the data written will be flushed to the file system before the returned future completes.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final file = File('${tmp.path}/b.bin');
await file.writeAsBytes([1, 2, 3]);
await file.writeAsBytes([4, 5], mode: FileMode.append);
print('appended: ${await file.readAsBytes()}');
await file.writeAsBytes([9]);
print('replaced: ${await file.readAsBytes()}');
await tmp.delete(recursive: true);
}appended: [1, 2, 3, 4, 5] replaced: [9]
void writeAsBytesSync(List<int> bytes, {FileMode mode = FileMode.write, bool flush = false})Synchronously writes a list of bytes to a file.
Opens the file, writes the list of bytes to it and closes the file.
By default writeAsBytesSync creates the file for writing and truncates the file if it already exists. In order to append the bytes to an existing file, pass FileMode.append as the optional mode parameter.
The elements of bytes should be integers in the range 0 to 255. Any integer, which is not in that range, is converted to a byte before being written. The conversion is equivalent to doing value.toUnsigned(8).
If the flush argument is set to true data written will be flushed to the file system before returning.
Throws a FileSystemException if the operation fails.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final file = File('${tmp.path}/ramp.bin');
file.writeAsBytesSync([for (var i = 0; i < 8; i++) i * 32], flush: true);
print('bytes: ${file.readAsBytesSync()}');
// Values are stored modulo 256.
file.writeAsBytesSync([256, 257, -1]);
print('wrapped: ${file.readAsBytesSync()}');
tmp.deleteSync(recursive: true);
}bytes: [0, 32, 64, 96, 128, 160, 192, 224] wrapped: [0, 1, 255]
Future<File> writeAsString(String contents, {FileMode mode = FileMode.write, Encoding encoding = utf8, bool flush = false})Writes a string to a file.
Opens the file, writes the string in the given encoding, and closes the file. Returns a Future<File> that completes with this File object once the entire operation has completed.
By default writeAsString creates the file for writing and truncates the file if it already exists. In order to append the bytes to an existing file, pass FileMode.append as the optional mode parameter.
If the argument flush is set to true, the data written will be flushed to the file system before the returned future completes.
This method does not transform newline characters ("\n") to the platform conventional line ending (e.g. "\r\n" on Windows). Use Platform.lineTerminator to separate lines in contents if platform conventional line endings are needed.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final log = File('${tmp.path}/app.log');
for (final msg in ['start', 'work', 'stop']) {
await log.writeAsString('$msg\n', mode: FileMode.append);
}
print(await log.readAsString());
await tmp.delete(recursive: true);
}start work stop
void writeAsStringSync(String contents, {FileMode mode = FileMode.write, Encoding encoding = utf8, bool flush = false})Synchronously writes a string to a file.
Opens the file, writes the string in the given encoding, and closes the file.
By default writeAsStringSync creates the file for writing and truncates the file if it already exists. In order to append the bytes to an existing file, pass FileMode.append as the optional mode parameter.
If the flush argument is set to true, data written will be flushed to the file system before returning.
This method does not transform newline characters ("\n") to the platform conventional line ending (e.g. "\r\n" on Windows). Use Platform.lineTerminator to separate lines in contents if platform conventional line endings are needed.
Throws a FileSystemException if the operation fails.
import 'raya:io';
import 'raya:convert';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final file = File('${tmp.path}/t.txt');
file.writeAsStringSync('été');
print('utf8 bytes: ${file.readAsBytesSync()}');
file.writeAsStringSync('été', encoding: latin1);
print('latin1 bytes: ${file.readAsBytesSync()}');
tmp.deleteSync(recursive: true);
}utf8 bytes: [195, 169, 116, 195, 169] latin1 bytes: [233, 116, 233]
RandomAccessFile
abstract interface class RandomAccessFile
Random access to the data in a file.
RandomAccessFile objects are obtained by calling the open method on a File object.
A RandomAccessFile has both asynchronous and synchronous methods. The asynchronous methods all return a Future whereas the synchronous methods will return the result directly, and block the current isolate until the result is ready.
At most one asynchronous method can be pending on a given RandomAccessFile instance at the time. If another asynchronous method is called when one is already in progress, a FileSystemException is thrown.
If an asynchronous method is pending, it is also not possible to call any synchronous methods. This will also throw a FileSystemException.
Properties
Methods
Future<void> close()Closes the file.
Returns a Future that completes when it has been closed.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final raf = await File('${tmp.path}/a.bin').open(mode: FileMode.write);
await raf.writeString('saved');
await raf.close();
print('content after close: ${File('${tmp.path}/a.bin').readAsStringSync()}');
try {
await raf.length();
} on FileSystemException {
print('using it after close: FileSystemException');
}
tmp.deleteSync(recursive: true);
}content after close: saved using it after close: FileSystemException
void closeSync()Synchronously closes the file.
Throws a FileSystemException if the operation fails.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final raf = File('${tmp.path}/b.bin').openSync(mode: FileMode.write);
raf.writeFromSync([1, 2, 3]);
raf.closeSync();
print('bytes on disk: ${File('${tmp.path}/b.bin').readAsBytesSync()}');
tmp.deleteSync(recursive: true);
}bytes on disk: [1, 2, 3]
Future<int> readByte()Reads a byte from the file.
Returns a Future<int> that completes with the byte, or with -1 if end-of-file has been reached.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final f = File('${tmp.path}/c.txt')..writeAsStringSync('AB');
final raf = await f.open();
print('${await raf.readByte()}, ${await raf.readByte()}, ${await raf.readByte()} (-1 = end)');
await raf.close();
tmp.deleteSync(recursive: true);
}65, 66, -1 (-1 = end)
int readByteSync()Synchronously reads a single byte from the file.
If end-of-file has been reached -1 is returned.
Throws a FileSystemException if the operation fails.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final raf = (File('${tmp.path}/d.txt')..writeAsStringSync('hi!')).openSync();
final bytes = <int>[];
for (int b; (b = raf.readByteSync()) != -1;) bytes.add(b);
print('bytes: $bytes -> ${String.fromCharCodes(bytes)}');
raf.closeSync();
tmp.deleteSync(recursive: true);
}bytes: [104, 105, 33] -> hi!
Future<Uint8List> read(int count)Reads up to count bytes from a file.
May return fewer than count bytes. This can happen, for example, when reading past the end of a file or when reading from a pipe that does not currently contain additional data.
An empty Uint8List will only be returned when reading past the end of the file or when count is 0.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final raf = await (File('${tmp.path}/e.txt')..writeAsStringSync('0123456789')).open();
print('read(4): ${String.fromCharCodes(await raf.read(4))}');
print('read(4): ${String.fromCharCodes(await raf.read(4))}');
print('read(4): ${String.fromCharCodes(await raf.read(4))} (only 2 left)');
await raf.close();
tmp.deleteSync(recursive: true);
}read(4): 0123 read(4): 4567 read(4): 89 (only 2 left)
Uint8List readSync(int count)Synchronously reads up to count bytes from a file
May return fewer than count bytes. This can happen, for example, when reading past the end of a file or when reading from a pipe that does not currently contain additional data.
An empty Uint8List will only be returned when reading past the end of the file or when count is 0.
Throws a FileSystemException if the operation fails.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final raf = (File('${tmp.path}/f.bin')..writeAsBytesSync([9, 8, 7, 6, 5])).openSync();
raf.setPositionSync(2);
print('readSync(2) from offset 2: ${raf.readSync(2)}');
raf.closeSync();
tmp.deleteSync(recursive: true);
}readSync(2) from offset 2: [7, 6]
Future<int> readInto(List<int> buffer, [int start = 0, int? end])Reads bytes into an existing buffer.
Reads bytes and writes them into the range of buffer from start to end. The start must be non-negative and no greater than buffer.length. If end is omitted, it defaults to buffer.length. Otherwise end must be no less than start and no greater than buffer.length.
Returns the number of bytes read. This maybe be less than end - start if the file doesn't have that many bytes to read.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final raf = await (File('${tmp.path}/g.bin')..writeAsBytesSync([1, 2, 3])).open();
final buf = List.filled(6, 0);
final n = await raf.readInto(buf, 2);
print('read $n bytes into the buffer from index 2: $buf');
await raf.close();
tmp.deleteSync(recursive: true);
}read 3 bytes into the buffer from index 2: [0, 0, 1, 2, 3, 0]
int readIntoSync(List<int> buffer, [int start = 0, int? end])Synchronously reads into an existing buffer.
Reads bytes and writes them into the range of buffer from start to end. The start must be non-negative and no greater than buffer.length. If end is omitted, it defaults to buffer.length. Otherwise end must be no less than start and no greater than buffer.length.
Returns the number of bytes read. This maybe be less than end - start if the file doesn't have that many bytes to read.
Throws a FileSystemException if the operation fails.
import 'raya:io';
import 'raya:typed_data';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final raf = (File('${tmp.path}/h.bin')..writeAsBytesSync(List.generate(10, (i) => i))).openSync();
final buf = Uint8List(4);
var chunks = <List<int>>[];
for (int n; (n = raf.readIntoSync(buf)) > 0;) chunks.add(buf.sublist(0, n));
print('read in 4-byte chunks: $chunks');
raf.closeSync();
tmp.deleteSync(recursive: true);
}read in 4-byte chunks: [[0, 1, 2, 3], [4, 5, 6, 7], [8, 9]]
Future<RandomAccessFile> writeByte(int value)Writes a single byte to the file.
Returns a Future<RandomAccessFile> that completes with this random access file when the write completes.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final f = File('${tmp.path}/i.bin');
final raf = await f.open(mode: FileMode.write);
for (final b in [0xCA, 0xFE]) {
await raf.writeByte(b);
}
await raf.close();
print('file bytes: ${f.readAsBytesSync().map((b) => b.toRadixString(16)).toList()}');
tmp.deleteSync(recursive: true);
}file bytes: [ca, fe]
int writeByteSync(int value)Synchronously writes a single byte to the file.
Returns 1 on success.
Throws a FileSystemException if the operation fails.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final f = File('${tmp.path}/j.txt');
final raf = f.openSync(mode: FileMode.write);
'OK\n'.codeUnits.forEach(raf.writeByteSync);
raf.closeSync();
print('file: ${f.readAsStringSync().trim()}');
tmp.deleteSync(recursive: true);
}file: OK
Future<RandomAccessFile> writeFrom(List<int> buffer, [int start = 0, int? end])Writes from a buffer to the file.
Will read the buffer from index start to index end. The start must be non-negative and no greater than buffer.length. If end is omitted, it defaults to buffer.length. Otherwise end must be no less than start and no greater than buffer.length.
Returns a Future<RandomAccessFile> that completes with this RandomAccessFile when the write completes.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final f = File('${tmp.path}/k.bin');
final raf = await f.open(mode: FileMode.write);
await raf.writeFrom([10, 20, 30, 40, 50], 1, 4);
await raf.close();
print('wrote bytes 1..4: ${f.readAsBytesSync()}');
tmp.deleteSync(recursive: true);
}wrote bytes 1..4: [20, 30, 40]
void writeFromSync(List<int> buffer, [int start = 0, int? end])Synchronously writes from a buffer to the file.
Will read the buffer from index start to index end. The start must be non-negative and no greater than buffer.length. If end is omitted, it defaults to buffer.length. Otherwise end must be no less than start and no greater than buffer.length.
Throws a FileSystemException if the operation fails.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final f = File('${tmp.path}/l.bin');
final raf = f.openSync(mode: FileMode.write);
raf.writeFromSync([1, 2, 3]);
raf.writeFromSync([4, 5, 6], 1);
raf.closeSync();
print('file: ${f.readAsBytesSync()}');
tmp.deleteSync(recursive: true);
}file: [1, 2, 3, 5, 6]
Future<RandomAccessFile> writeString(String string, {Encoding encoding = utf8})Writes a string to the file using the given Encoding.
Returns a Future<RandomAccessFile> that completes with this random access file when the write completes.
import 'raya:io';
import 'raya:convert';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final f = File('${tmp.path}/m.txt');
final raf = await f.open(mode: FileMode.write);
await raf.writeString('café');
print('utf8 length: ${await raf.length()}');
await raf.setPosition(0);
await raf.truncate(0);
await raf.writeString('café', encoding: latin1);
print('latin1 length: ${await raf.length()}');
await raf.close();
tmp.deleteSync(recursive: true);
}utf8 length: 5 latin1 length: 4
void writeStringSync(String string, {Encoding encoding = utf8})Synchronously writes a single string to the file using the given Encoding.
Throws a FileSystemException if the operation fails.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final f = File('${tmp.path}/n.log');
final raf = f.openSync(mode: FileMode.append);
for (var i = 1; i <= 3; i++) {
raf.writeStringSync('entry $i\n');
}
raf.closeSync();
print(f.readAsLinesSync());
tmp.deleteSync(recursive: true);
}[entry 1, entry 2, entry 3]
Future<int> position()Gets the current byte position in the file.
Returns a Future<int> that completes with the position.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final raf = await (File('${tmp.path}/o.txt')..writeAsStringSync('abcdef')).open();
print('start: ${await raf.position()}');
await raf.read(4);
print('after read(4): ${await raf.position()}');
await raf.close();
tmp.deleteSync(recursive: true);
}start: 0 after read(4): 4
int positionSync()Synchronously gets the current byte position in the file.
Throws a FileSystemException if the operation fails.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final raf = File('${tmp.path}/p.txt').openSync(mode: FileMode.write);
raf.writeStringSync('hello');
print('position after writing 5 bytes: ${raf.positionSync()}');
raf.closeSync();
tmp.deleteSync(recursive: true);
}position after writing 5 bytes: 5
Future<RandomAccessFile> setPosition(int position)Sets the byte position in the file.
Returns a Future<RandomAccessFile> that completes with this random access file when the position has been set.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final f = File('${tmp.path}/q.txt')..writeAsStringSync('hello world');
final raf = await f.open();
await raf.setPosition(6);
print('from offset 6: ${String.fromCharCodes(await raf.read(5))}');
await raf.setPosition(0);
print('back to 0: ${String.fromCharCodes(await raf.read(5))}');
await raf.close();
tmp.deleteSync(recursive: true);
}from offset 6: world back to 0: hello
void setPositionSync(int position)Synchronously sets the byte position in the file.
Throws a FileSystemException if the operation fails.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final f = File('${tmp.path}/r.txt')..writeAsStringSync('hello world');
final raf = f.openSync(mode: FileMode.write);
raf.writeStringSync('hello world');
raf.setPositionSync(6);
raf.writeStringSync('WORLD');
raf.closeSync();
print(f.readAsStringSync());
tmp.deleteSync(recursive: true);
}hello WORLD
Future<RandomAccessFile> truncate(int length)Truncates (or extends) the file to length bytes.
Returns a Future<RandomAccessFile> that completes with this random access file when the truncation has been performed.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final f = File('${tmp.path}/s.txt')..writeAsStringSync('keep|drop');
final raf = await f.open(mode: FileMode.append);
await raf.truncate(4);
await raf.close();
print('after truncate(4): ${f.readAsStringSync()}');
tmp.deleteSync(recursive: true);
}after truncate(4): keep
void truncateSync(int length)Synchronously truncates (or extends) the file to length bytes.
Throws a FileSystemException if the operation fails.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final f = File('${tmp.path}/t.bin');
final raf = f.openSync(mode: FileMode.write);
raf.truncateSync(8); // grows the file with zero bytes
raf.closeSync();
print('after truncateSync(8): ${f.readAsBytesSync()}');
tmp.deleteSync(recursive: true);
}after truncateSync(8): [0, 0, 0, 0, 0, 0, 0, 0]
Future<int> length()Gets the length of the file.
Returns a Future<int> that completes with the length in bytes.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final raf = await File('${tmp.path}/u.txt').open(mode: FileMode.write);
print('empty: ${await raf.length()}');
await raf.writeString('twelve bytes');
print('after writing: ${await raf.length()}');
await raf.close();
tmp.deleteSync(recursive: true);
}empty: 0 after writing: 12
int lengthSync()Synchronously gets the length of the file.
Throws a FileSystemException if the operation fails.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final raf = (File('${tmp.path}/v.bin')..writeAsBytesSync(List.filled(1024, 0))).openSync();
print('lengthSync: ${raf.lengthSync()} bytes');
raf.closeSync();
tmp.deleteSync(recursive: true);
}lengthSync: 1024 bytes
Future<RandomAccessFile> flush()Flushes the contents of the file to disk.
Returns a Future<RandomAccessFile> that completes with this random access file when the flush operation completes.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final f = File('${tmp.path}/w.txt');
final raf = await f.open(mode: FileMode.write);
await raf.writeString('durable');
await raf.flush(); // pushed to the OS before close
print('visible before close: ${f.readAsStringSync()}');
await raf.close();
tmp.deleteSync(recursive: true);
}visible before close: durable
void flushSync()Synchronously flushes the contents of the file to disk.
Throws a FileSystemException if the operation fails.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final f = File('${tmp.path}/x.txt');
final raf = f.openSync(mode: FileMode.write);
raf.writeStringSync('line 1\n');
raf.flushSync();
print('another reader sees: ${f.readAsStringSync().trim()}');
raf.closeSync();
tmp.deleteSync(recursive: true);
}another reader sees: line 1
Future<RandomAccessFile> lock([FileLock mode = FileLock.exclusive, int start = 0, int end = -1])Locks the file or part of the file.
By default an exclusive lock will be obtained, but that can be overridden by the mode argument.
Locks the byte range from start to end of the file, with the byte at position end not included. If no arguments are specified, the full file is locked, If only start is specified the file is locked from byte position start to the end of the file, no matter how large it grows. It is possible to specify an explicit value of end which is past the current length of the file.
To obtain an exclusive lock on a file, it must be opened for writing.
If mode is FileLock.exclusive or FileLock.shared, an error is signaled if the lock cannot be obtained. If mode is FileLock.blockingExclusive or FileLock.blockingShared, the returned Future is resolved only when the lock has been obtained.
NOTE file locking does have slight differences in behavior across platforms:
On Linux and OS X this uses advisory locks, which have the surprising semantics that all locks associated with a given file are removed when any file descriptor for that file is closed by the process. Note that this does not actually lock the file for access. Also note that advisory locks are on a process level. This means that several isolates in the same process can obtain an exclusive lock on the same file.
On Windows the regions used for lock and unlock needs to match. If that is not the case unlocking will result in the OS error "The segment is already unlocked".
On Windows, locking a file associates the lock with the specific file handle used to acquire the lock. If the same file is opened again with a different handle (even within the same process), attempts to write to the locked region using the new handle will fail. To ensure successful writes after locking, use the same RandomAccessFile object that acquired the lock for subsequent write operations.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final raf = await File('${tmp.path}/app.lock').open(mode: FileMode.write);
await raf.lock(FileLock.exclusive);
print('holding an exclusive lock');
await raf.writeString('pid file contents');
await raf.unlock();
print('released');
await raf.close();
tmp.deleteSync(recursive: true);
}holding an exclusive lock released
void lockSync([FileLock mode = FileLock.exclusive, int start = 0, int end = -1])Synchronously locks the file or part of the file.
By default an exclusive lock will be obtained, but that can be overridden by the mode argument.
Locks the byte range from start to end of the file,with the byte at position end not included. If no arguments are specified, the full file is locked, If only start is specified the file is locked from byte position start to the end of the file, no matter how large it grows. It is possible to specify an explicit value of end which is past the current length of the file.
To obtain an exclusive lock on a file it must be opened for writing.
If mode is FileLock.exclusive or FileLock.shared, an exception is thrown if the lock cannot be obtained. If mode is FileLock.blockingExclusive or FileLock.blockingShared, the call returns only after the lock has been obtained.
NOTE file locking does have slight differences in behavior across platforms:
On Linux and OS X this uses advisory locks, which have the surprising semantics that all locks associated with a given file are removed when any file descriptor for that file is closed by the process. Note that this does not actually lock the file for access. Also note that advisory locks are on a process level. This means that several isolates in the same process can obtain an exclusive lock on the same file.
On Windows the regions used for lock and unlock needs to match. If that is not the case unlocking will result in the OS error "The segment is already unlocked".
On Windows, locking a file associates the lock with the specific file handle used to acquire the lock. If the same file is opened again with a different handle (even within the same process), attempts to write to the locked region using the new handle will fail. To ensure successful writes after locking, use the same RandomAccessFile object that acquired the lock for subsequent write operations.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final raf = File('${tmp.path}/data.db').openSync(mode: FileMode.write);
raf.writeFromSync(List.filled(100, 0));
raf.lockSync(FileLock.shared, 0, 50); // lock only the first 50 bytes
print('locked bytes 0..50 for shared reading');
raf.unlockSync(0, 50);
raf.closeSync();
tmp.deleteSync(recursive: true);
}locked bytes 0..50 for shared reading
Future<RandomAccessFile> unlock([int start = 0, int end = -1])Unlocks the file or part of the file.
Unlocks the byte range from start to end of the file, with the byte at position end not included. If no arguments are specified, the full file is unlocked, If only start is specified the file is unlocked from byte position start to the end of the file.
NOTE file locking does have slight differences in behavior across platforms:
See lock for more details.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final raf = await File('${tmp.path}/q.lock').open(mode: FileMode.write);
await raf.lock(FileLock.blockingExclusive);
print('locked');
await raf.unlock();
await raf.lock(FileLock.exclusive);
print('unlocked and locked again');
await raf.close();
tmp.deleteSync(recursive: true);
}locked unlocked and locked again
void unlockSync([int start = 0, int end = -1])Synchronously unlocks the file or part of the file.
Unlocks the byte range from start to end of the file, with the byte at position end not included. If no arguments are specified, the full file is unlocked, If only start is specified the file is unlocked from byte position start to the end of the file.
NOTE file locking does have slight differences in behavior across platforms:
See lockSync for more details.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final raf = File('${tmp.path}/r.lock').openSync(mode: FileMode.write);
raf.lockSync();
raf.unlockSync();
print('lockSync then unlockSync: ok');
raf.closeSync();
tmp.deleteSync(recursive: true);
}lockSync then unlockSync: ok
String toString()Returns a human-readable string for this random access file.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final raf = File('${tmp.path}/notes.txt').openSync(mode: FileMode.write);
print('toString: $raf');
print('path: ${raf.path.replaceAll(tmp.path, '<tmp>')}');
raf.closeSync();
tmp.deleteSync(recursive: true);
}toString: Instance of '_RandomAccessFile' path: <tmp>/notes.txt
FileSystemException
class FileSystemException implements IOException
Exception thrown when a file operation fails.
Constructors
const FileSystemException([this.message = "", this.path = "", this.osError])Creates a new file system exception with optional parts.
Creates an exception with FileSystemException.message, FileSystemException.path and FileSystemException.osError values take from the optional parameters of the same name.
The message and path path defaults to empty strings if omitted, and osError defaults to null.
import 'raya:io';
void main() {
const e = FileSystemException('Cannot open', 'config.yaml', OSError('No such file or directory', 2));
print('message: ${e.message}, path: ${e.path}, errno: ${e.osError?.errorCode}');
try {
File('definitely/missing/file.txt').readAsStringSync();
} on FileSystemException catch (e) {
print('caught for path: ${e.path}');
}
}message: Cannot open, path: config.yaml, errno: 2 caught for path: definitely/missing/file.txt
Properties
final String messageMessage describing the error.
The message does not include any detailed information from the underlying OS error. Check osError for that information.
final String? pathThe file system path on which the error occurred.
Can be null if the exception does not relate directly to a file system path.
final OSError? osErrorThe underlying OS error.
Can be null if the exception is not raised due to an OS error.
Methods
String toString()import 'raya:io';
void main() {
print(const FileSystemException('Cannot delete', 'a.txt'));
print(const FileSystemException('Cannot read', 'b.txt', OSError('Permission denied', 13)));
}FileSystemException: Cannot delete, path = 'a.txt' FileSystemException: Cannot read, path = 'b.txt' (OS Error: Permission denied, errno = 13)
PathAccessException
class PathAccessException extends FileSystemException
Exception thrown when a file operation fails because the necessary access rights are not available.
Constructors
const PathAccessException(String path, OSError osError, [String message = ""])import 'raya:io';
void main() {
const e = PathAccessException('/root/secret', OSError('Permission denied', 13), 'Cannot open file');
print('is a FileSystemException: ${e is FileSystemException}');
print('path: ${e.path}, errno: ${e.osError!.errorCode}');
}is a FileSystemException: true path: /root/secret, errno: 13
Methods
String toString()import 'raya:io';
void main() {
print(const PathAccessException('locked.txt', OSError('Permission denied', 13), 'Cannot write'));
}PathAccessException: Cannot write, path = 'locked.txt' (OS Error: Permission denied, errno = 13)
PathExistsException
class PathExistsException extends FileSystemException
Exception thrown when a file operation fails because the target path already exists.
Constructors
const PathExistsException(String path, OSError osError, [String message = ""])import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final d = Directory('${tmp.path}/x')..createSync();
try {
File(d.path).createSync(exclusive: true);
} on FileSystemException catch (e) {
print('creating over an existing path: ${e.runtimeType}');
}
print(const PathExistsException('x', OSError('File exists', 17)).path);
tmp.deleteSync(recursive: true);
}creating over an existing path: PathExistsException x
Methods
String toString()import 'raya:io';
void main() {
print(const PathExistsException('out', OSError('File exists', 17), 'Creation failed'));
}PathExistsException: Creation failed, path = 'out' (OS Error: File exists, errno = 17)
class PathNotFoundException extends FileSystemException
Exception thrown when a file operation fails because a file or directory does not exist.
Constructors
const PathNotFoundException(String path, OSError osError, [String message = ""])import 'raya:io';
void main() {
try {
File('no/such/file.txt').readAsStringSync();
} on PathNotFoundException catch (e) {
print('PathNotFoundException for ${e.path}, errno ${e.osError?.errorCode}');
}
}PathNotFoundException for no/such/file.txt, errno 2
Methods
String toString()import 'raya:io';
void main() {
print(const PathNotFoundException('missing.txt', OSError('No such file or directory', 2), 'Cannot open file'));
}PathNotFoundException: Cannot open file, path = 'missing.txt' (OS Error: No such file or directory, errno = 2)
ReadPipe
abstract interface class ReadPipe implements Stream<List<int>>
The "read" end of an Pipe created by Pipe.create.
The read stream will continue to listen until the "write" end of the pipe (i.e. Pipe.write) is closed.
final pipe = await Pipe.create();
pipe.read.transform(utf8.decoder).listen((data) {
print(data);
}, onDone: () => print('Done'));WritePipe
abstract interface class WritePipe implements IOSink
The "write" end of an Pipe created by Pipe.create.
final pipe = await Pipe.create();
pipe.write.add("Hello World!".codeUnits);
await pipe.write.flush();
await pipe.write.close();Pipe
abstract interface class Pipe
An anonymous pipe that can be used to send data in a single direction i.e. data written to write can be read using read.
On macOS and Linux (excluding Android), either the read or write portion of the pipe can be transmitted to another process and used for interprocess communication.
For example:
final pipe = await Pipe.create();
final socket = await RawSocket.connect(address, 0);
socket.sendMessage(<SocketControlMessage>[
SocketControlMessage.fromHandles(
<ResourceHandle>[ResourceHandle.fromReadPipe(pipe.read)])
], 'Hello'.codeUnits);
pipe.write.add('Hello over pipe!'.codeUnits);
await pipe.write.flush();
await pipe.write.close();Constructors
factory Pipe.createSync()Synchronously creates an anonymous pipe.
import 'raya:io';
import 'raya:convert';
Future<void> main() async {
final pipe = Pipe.createSync();
pipe.write.add(utf8.encode('through the pipe'));
await pipe.write.close();
print(await pipe.read.transform(utf8.decoder).join());
}through the pipe
Static
static Future<Pipe> create()import 'raya:io';
import 'raya:convert';
Future<void> main() async {
final pipe = await Pipe.create();
pipe.write.writeln('line one');
pipe.write.writeln('line two');
await pipe.write.close();
print(await pipe.read.transform(utf8.decoder).transform(const LineSplitter()).toList());
}[line one, line two]
Properties
FileSystemEntityType
final class FileSystemEntityType
The type of an entity on the file system, such as a file, directory, or link.
These constants are used by the FileSystemEntity class to indicate the object's type.
Static
static const file = const FileSystemEntityType._internal(0)static const directory = const FileSystemEntityType._internal(1)static const link = const FileSystemEntityType._internal(2)static const unixDomainSock = const FileSystemEntityType._internal(3)static const pipe = const FileSystemEntityType._internal(4)static const notFound = const FileSystemEntityType._internal(5)static const NOT_FOUND = notFoundMethods
String toString()import 'raya:io';
void main() {
for (final t in [FileSystemEntityType.file, FileSystemEntityType.directory, FileSystemEntityType.link, FileSystemEntityType.notFound]) {
print(t);
}
}file directory link notFound
FileStat
interface class FileStat
The result of calling the POSIX stat function on a file system object.
This is an immutable object, representing the snapshotted values returned by the stat call.
Static
static FileStat statSync(String path)Calls the operating system's stat function (or equivalent) on path.
If path is a symbolic link then it is resolved and results for the resulting file are returned.
Returns a FileStat object containing the data returned by stat. If the call fails, returns a FileStat object with FileStat.type set to FileSystemEntityType.notFound and the other fields invalid.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final f = File('${tmp.path}/a.txt')..writeAsStringSync('12345');
final s = FileStat.statSync(f.path);
print('type: ${s.type}, size: ${s.size}');
print('missing: ${FileStat.statSync('${tmp.path}/nope').type}');
tmp.deleteSync(recursive: true);
}type: file, size: 5 missing: notFound
static Future<FileStat> stat(String path)Asynchronously calls the operating system's stat function (or equivalent) on path.
If path is a symbolic link then it is resolved and results for the resulting file are returned.
Returns a Future which completes with the same results as statSync.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final s = await FileStat.stat(tmp.path);
print('temp dir type: ${s.type}');
print('modified is a DateTime: ${s.modified is DateTime}');
tmp.deleteSync(recursive: true);
}temp dir type: directory modified is a DateTime: true
Properties
final DateTime changedThe time of the last change to the data or metadata of the file system object.
On Windows platforms, this is instead the file creation time.
final DateTime modifiedThe time of the last change to the data of the file system object.
final DateTime accessedThe time of the last access to the data of the file system object.
On Windows platforms, this may have 1 day granularity, and be out of date by an hour.
final FileSystemEntityType typeThe type of the underlying file system object.
FileSystemEntityType.notFound if stat or statSync failed.
final int modeThe mode of the file system object.
Permissions are encoded in the lower 16 bits of this number, and can be decoded using the modeString getter.
Methods
String toString()import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final f = File('${tmp.path}/a.txt')..writeAsStringSync('abc');
final lines = f.statSync().toString().split('\n');
// The first line names the type; the rest list times and mode.
print(lines.first);
print('lines: ${lines.length}, mentions mode: ${lines.any((l) => l.trim().startsWith('mode'))}');
tmp.deleteSync(recursive: true);
}FileStat: type file lines: 6, mentions mode: true
String modeString()The mode value as a human-readable string.
The string is in the format "rwxrwxrwx", reflecting the user, group, and world permissions to read, write, and execute the file system object, with "-" replacing the letter for missing permissions. Extra permission bits may be represented by prepending "(suid)", "(guid)", and/or "(sticky)" to the mode string.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final f = File('${tmp.path}/run.sh')..writeAsStringSync('echo hi');
Process.runSync('chmod', ['750', f.path]);
print('mode: ${f.statSync().modeString()}');
tmp.deleteSync(recursive: true);
}mode: rwxr-x---
FileSystemEntity
abstract class FileSystemEntity
The common superclass of File, Directory, and Link.
FileSystemEntity objects are returned from directory listing operations. To determine whether a FileSystemEntity is a File, a Directory, or a Link perform a type check:
if (entity is File) (entity as File).readAsStringSync();
You can also use the type or typeSync methods to determine the type of a file system object.
Most methods in this class exist both in synchronous and asynchronous versions, for example, exists and existsSync. Unless you have a specific reason for using the synchronous version of a method, prefer the asynchronous version to avoid blocking your program.
Here's the exists method in action:
var isThere = await entity.exists();
print(isThere ? 'exists' : 'nonexistent');Static
static Future<bool> identical(String path1, String path2)Checks whether two paths refer to the same object in the file system.
Returns a Future<bool> that completes with the result.
Comparing a link to its target returns false, as does comparing two links that point to the same target. To check the target of a link, use Link.target explicitly to fetch it. Directory links appearing inside a path are followed, though, to find the file system object.
Completes the returned Future with an error if one of the paths points to an object that does not exist.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final f = File('${tmp.path}/a.txt')..writeAsStringSync('a');
Link('${tmp.path}/ln').createSync(f.path);
File('${tmp.path}/b.txt').writeAsStringSync('a');
print('a vs ./a: ${await FileSystemEntity.identical(f.path, '${tmp.path}/./a.txt')}');
print('a vs link: ${await FileSystemEntity.identical(f.path, '${tmp.path}/ln')}');
print('a vs copy: ${await FileSystemEntity.identical(f.path, '${tmp.path}/b.txt')}');
await tmp.delete(recursive: true);
}a vs ./a: true a vs link: false a vs copy: false
static bool identicalSync(String path1, String path2)Synchronously checks whether two paths refer to the same object in the file system.
Comparing a link to its target returns false, as does comparing two links that point to the same target. To check the target of a link, use Link.target explicitly to fetch it. Directory links appearing inside a path are followed, though, to find the file system object.
Throws an error if one of the paths points to an object that does not exist.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
Directory('${tmp.path}/x/y').createSync(recursive: true);
print('x/y/.. is x: ${FileSystemEntity.identicalSync('${tmp.path}/x/y/..', '${tmp.path}/x')}');
print('x is x/y: ${FileSystemEntity.identicalSync('${tmp.path}/x', '${tmp.path}/x/y')}');
tmp.deleteSync(recursive: true);
}x/y/.. is x: true x is x/y: false
static bool get isWatchSupportedTest if watch is supported on the current system.
OS X 10.6 and below is not supported.
static Future<FileSystemEntityType> type(String path, {bool followLinks = true})Finds the type of file system object that a path points to.
Returns a Future<FileSystemEntityType> that completes with the same results as typeSync.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
File('${tmp.path}/f').writeAsStringSync('');
Link('${tmp.path}/l').createSync('${tmp.path}/f');
for (final n in ['f', 'l', 'missing']) {
print('$n: ${await FileSystemEntity.type('${tmp.path}/$n')}');
}
print('l, links followed off: ${await FileSystemEntity.type('${tmp.path}/l', followLinks: false)}');
print('tmp: ${await FileSystemEntity.type(tmp.path)}');
await tmp.delete(recursive: true);
}f: file l: file missing: notFound l, links followed off: link tmp: directory
static FileSystemEntityType typeSync(String path, {bool followLinks = true})Synchronously finds the type of file system object that a path points to.
Returns FileSystemEntityType.notFound if path does not point to a file system object or if any other error occurs in looking up the path.
If path points to a link and followLinks is true then the result will be for the file system object that the link points to. If that object does not exist then the result will be FileSystemEntityType.notFound. If path points to a link and followLinks is false then the result will be FileSystemEntityType.link.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
File('${tmp.path}/data.csv').writeAsStringSync('1,2');
Directory('${tmp.path}/out').createSync();
for (final n in ['data.csv', 'out', 'nope']) {
final t = FileSystemEntity.typeSync('${tmp.path}/$n');
final label = switch (t) {
FileSystemEntityType.file => 'a file',
FileSystemEntityType.directory => 'a directory',
FileSystemEntityType.notFound => 'not there',
_ => 'something else',
};
print('$n is $label');
}
tmp.deleteSync(recursive: true);
}data.csv is a file out is a directory nope is not there
static Future<bool> isLink(String path)Whether path refers to a link.
Checks whether type(path, followLinks: false) returns FileSystemEntityType.link.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final f = File('${tmp.path}/f')..writeAsStringSync('');
Link('${tmp.path}/l').createSync(f.path);
print('l is a link: ${await FileSystemEntity.isLink('${tmp.path}/l')}');
print('f is a link: ${await FileSystemEntity.isLink(f.path)}');
await tmp.delete(recursive: true);
}l is a link: true f is a link: false
static Future<bool> isFile(String path)Whether path refers to a file.
Checks whether type(path) returns FileSystemEntityType.file.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final f = File('${tmp.path}/f')..writeAsStringSync('');
Link('${tmp.path}/l').createSync(f.path);
print('f: ${await FileSystemEntity.isFile(f.path)}');
print('l (link to a file, followed): ${await FileSystemEntity.isFile('${tmp.path}/l')}');
print('tmp: ${await FileSystemEntity.isFile(tmp.path)}');
await tmp.delete(recursive: true);
}f: true l (link to a file, followed): true tmp: false
static Future<bool> isDirectory(String path)Whether path refers to a directory.
Checks whether type(path) returns FileSystemEntityType.directory.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
File('${tmp.path}/f').writeAsStringSync('');
print('tmp is a directory: ${await FileSystemEntity.isDirectory(tmp.path)}');
print('f is a directory: ${await FileSystemEntity.isDirectory('${tmp.path}/f')}');
print('missing: ${await FileSystemEntity.isDirectory('${tmp.path}/none')}');
await tmp.delete(recursive: true);
}tmp is a directory: true f is a directory: false missing: false
static bool isLinkSync(String path)Synchronously checks whether path refers to a link.
Checks whether typeSync(path, followLinks: false) returns FileSystemEntityType.link.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
Link('${tmp.path}/dangling').createSync('${tmp.path}/nothing-here');
print('dangling link is a link: ${FileSystemEntity.isLinkSync('${tmp.path}/dangling')}');
print('its target exists: ${File('${tmp.path}/dangling').existsSync()}');
tmp.deleteSync(recursive: true);
}dangling link is a link: true its target exists: false
static bool isFileSync(String path)Synchronously checks whether path refers to a file.
Checks whether typeSync(path) returns FileSystemEntityType.file.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
File('${tmp.path}/a.txt').writeAsStringSync('a');
Directory('${tmp.path}/b').createSync();
for (final n in ['a.txt', 'b']) {
print('$n isFile: ${FileSystemEntity.isFileSync('${tmp.path}/$n')}');
}
tmp.deleteSync(recursive: true);
}a.txt isFile: true b isFile: false
static bool isDirectorySync(String path)Synchronously checks whether path refers to a directory.
Checks whether typeSync(path) returns FileSystemEntityType.directory.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
Directory('${tmp.path}/real').createSync();
Link('${tmp.path}/alias').createSync('${tmp.path}/real');
print('real: ${FileSystemEntity.isDirectorySync('${tmp.path}/real')}');
print('alias (link followed): ${FileSystemEntity.isDirectorySync('${tmp.path}/alias')}');
tmp.deleteSync(recursive: true);
}real: true alias (link followed): true
static String parentOf(String path)The parent path of a path.
Finds the final path component of a path, using the platform's path separator to split the path, and returns the prefix up to that part.
Will not remove the root component of a Windows path, like "C:\\" or "\\\\server_name\\". Includes a trailing path separator in the last part of path, and leaves no trailing path separator.
import 'raya:io';
void main() {
for (final p in ['/usr/local/bin', '/usr/local/bin/', 'docs/readme.md', 'readme.md', '/']) {
print('parentOf("$p") = "${FileSystemEntity.parentOf(p)}"');
}
}parentOf("/usr/local/bin") = "/usr/local"
parentOf("/usr/local/bin/") = "/usr/local"
parentOf("docs/readme.md") = "docs"
parentOf("readme.md") = "."
parentOf("/") = "/"Properties
String get pathUri get uribool get isAbsoluteWhether this object's path is absolute.
An absolute path is independent of the current working directory (Directory.current). A non-absolute path must be interpreted relative to the current working directory.
On Windows, a path is absolute if it starts with \\ (two backslashes or representing a UNC path) or with a drive letter between a and z (upper or lower case) followed by :\ or :/. This makes, for example, \file.ext a non-absolute path because it depends on the current drive letter.
On non-Windows, a path is absolute if it starts with /.
If the path is not absolute, use absolute to get an entity with an absolute path referencing the same object in the file system, if possible.
FileSystemEntity get absoluteA FileSystemEntity whose path is the absolute path of path.
The type of the returned instance is the same as the type of this entity.
A file system entity with an already absolute path (as reported by isAbsolute) is returned directly. For a non-absolute path, the returned entity is absolute (isAbsolute) if possible, but still refers to the same file system object.
Methods
Future<bool> exists()Checks whether the file system entity with this path exists.
Returns a Future<bool> that completes with the result.
Since FileSystemEntity is abstract, every FileSystemEntity object is actually an instance of one of the subclasses File, Directory, and Link. Calling exists on an instance of one of these subclasses checks whether the object exists in the file system object exists and is of the correct type (file, directory, or link). To check whether a path points to an object on the file system, regardless of the object's type, use the type static method.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final file = File('${tmp.path}/maybe.txt');
print('before: ${await file.exists()}');
await file.writeAsString('now');
print('after: ${await file.exists()}');
// A File object does not exist as a Directory.
print('as dir: ${await Directory(file.path).exists()}');
await tmp.delete(recursive: true);
}before: false after: true as dir: false
bool existsSync()Synchronously checks whether the file system entity with this path exists.
Since FileSystemEntity is abstract, every FileSystemEntity object is actually an instance of one of the subclasses File, Directory, and Link. Calling existsSync on an instance of one of these subclasses checks whether the object exists in the file system object exists and is of the correct type (file, directory, or link). To check whether a path points to an object on the file system, regardless of the object's type, use the typeSync static method.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final cfg = File('${tmp.path}/settings.json');
if (!cfg.existsSync()) {
cfg.writeAsStringSync('{"theme": "dark"}');
print('created default settings');
}
print('exists now: ${cfg.existsSync()}');
print('contents: ${cfg.readAsStringSync()}');
tmp.deleteSync(recursive: true);
}created default settings
exists now: true
contents: {"theme": "dark"}Future<FileSystemEntity> rename(String newPath)Renames this file system entity.
Returns a Future<FileSystemEntity> that completes with a FileSystemEntity instance for the renamed file system entity.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final FileSystemEntity e = File('${tmp.path}/in.txt')..writeAsStringSync('payload');
final moved = await e.rename('${tmp.path}/out.txt');
print('moved type: ${moved.runtimeType == e.runtimeType}');
print('name: ${moved.path.split('/').last}');
print('old gone: ${!await e.exists()}');
await tmp.delete(recursive: true);
}moved type: true name: out.txt old gone: true
FileSystemEntity renameSync(String newPath)Synchronously renames this file system entity.
Returns a FileSystemEntity instance for the renamed entity.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final entities = <FileSystemEntity>[
File('${tmp.path}/f')..writeAsStringSync('f'),
Directory('${tmp.path}/d')..createSync(),
];
for (final e in entities) {
final r = e.renameSync('${e.path}_renamed');
print('${e.path.split('/').last} -> ${r.path.split('/').last}');
}
tmp.deleteSync(recursive: true);
}f -> f_renamed d -> d_renamed
Future<String> resolveSymbolicLinks()Resolves the path of a file system object relative to the current working directory.
Resolves all symbolic links on the path and resolves all .. and . path segments.
resolveSymbolicLinks uses the operating system's native file system API to resolve the path, using the realpath function on Linux and OS X, and the GetFinalPathNameByHandle function on Windows. If the path does not point to an existing file system object, resolveSymbolicLinks throws a FileSystemException.
On Windows the .. segments are resolved before resolving the symbolic link, and on other platforms the symbolic links are resolved to their target before applying a .. that follows.
To ensure the same behavior on all platforms resolve .. segments before calling resolveSymbolicLinks. One way of doing this is with the Uri class:
var path = Uri.parse('.').resolveUri(Uri.file(input)).toFilePath();
if (path == '') path = '.';
var resolved = await File(path).resolveSymbolicLinks();
print(resolved);
Since Uri.resolve removes .. segments. This will result in the Windows behavior.
On Windows, attempting to resolve a symbolic link where the link type does not match the type of the resolved file system object will cause the Future to complete with a PathAccessException error.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final root = await tmp.resolveSymbolicLinks();
File('$root/target.txt').writeAsStringSync('t');
Link('$root/link.txt').createSync('target.txt');
final real = await File('$root/link.txt').resolveSymbolicLinks();
print('link.txt resolves to ${real.substring(root.length + 1)}');
await tmp.delete(recursive: true);
}link.txt resolves to target.txt
String resolveSymbolicLinksSync()Resolves the path of a file system object relative to the current working directory.
Resolves all symbolic links on the path and resolves all .. and . path segments.
resolveSymbolicLinksSync uses the operating system's native file system API to resolve the path, using the realpath function on linux and OS X, and the GetFinalPathNameByHandle function on Windows. If the path does not point to an existing file system object, resolveSymbolicLinksSync throws a FileSystemException.
On Windows the .. segments are resolved before resolving the symbolic link, and on other platforms the symbolic links are resolved to their target before applying a .. that follows.
To ensure the same behavior on all platforms resolve .. segments before calling resolveSymbolicLinksSync. One way of doing this is with the Uri class:
var path = Uri.parse('.').resolveUri(Uri.file(input)).toFilePath();
if (path == '') path = '.';
var resolved = File(path).resolveSymbolicLinksSync();
print(resolved);
Since Uri.resolve removes .. segments. This will result in the Windows behavior.
On Windows, a symbolic link is created as either a file link or a directory link. Attempting to resolve such a symbolic link requires the link type to match the type of the file system object that it points to, otherwise it throws a PathAccessException.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final root = tmp.resolveSymbolicLinksSync();
try {
File('$root/missing').resolveSymbolicLinksSync();
} on FileSystemException {
print('missing path: FileSystemException');
}
Directory('$root/a/b').createSync(recursive: true);
final r = Directory('$root/a/./b/../b').resolveSymbolicLinksSync();
print('a/./b/../b -> ${r.substring(root.length + 1)}');
tmp.deleteSync(recursive: true);
}missing path: FileSystemException a/./b/../b -> a/b
Future<FileStat> stat()Calls the operating system's stat function on path.
Identical to FileStat.stat(this.path).
Returns a Future<FileStat> object containing the data returned by stat.
If path is a symbolic link then it is resolved and results for the resulting file are returned.
If the call fails, completes the future with a FileStat object with .type set to FileSystemEntityType.notFound and the other fields invalid.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final f = File('${tmp.path}/s.txt')..writeAsStringSync('12345');
final s = await f.stat();
print('type: ${s.type}');
print('size: ${s.size}');
final dirStat = await tmp.stat();
print('tmp type: ${dirStat.type}');
await tmp.delete(recursive: true);
}type: file size: 5 tmp type: directory
FileStat statSync()Synchronously calls the operating system's stat function on path.
Identical to FileStat.statSync(this.path).
Returns a FileStat object containing the data returned by stat.
If path is a symbolic link then it is resolved and results for the resulting file are returned.
If the call fails, returns a FileStat object with .type set to FileSystemEntityType.notFound and the other fields invalid.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final s = File('${tmp.path}/missing').statSync();
print('missing type: ${s.type}');
print('missing size: ${s.size}');
final f = File('${tmp.path}/x')..writeAsStringSync('abc');
f.setLastModifiedSync(DateTime.utc(2021, 5, 4));
final fs = f.statSync();
print('file: ${fs.type}, ${fs.size} bytes, modified ${fs.modified.toUtc().toIso8601String()}');
tmp.deleteSync(recursive: true);
}missing type: notFound missing size: -1 file: file, 3 bytes, modified 2021-05-04T00:00:00.000Z
Future<FileSystemEntity> delete({bool recursive = false})Deletes this FileSystemEntity.
The exact details vary according to the FileSystemEntity:
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final items = <FileSystemEntity>[
File('${tmp.path}/f.txt')..writeAsStringSync('f'),
Directory('${tmp.path}/d')..createSync(),
];
for (final e in items) {
await e.delete();
print('${e.path.split('/').last} deleted: ${!await e.exists()}');
}
await tmp.delete(recursive: true);
}f.txt deleted: true d deleted: true
void deleteSync({bool recursive = false})Synchronously deletes this FileSystemEntity.
The exact details vary according to the FileSystemEntity:
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final target = File('${tmp.path}/t.txt')..writeAsStringSync('keep me');
final link = Link('${tmp.path}/l')..createSync(target.path);
link.deleteSync(); // removes the link, not the target
print('link gone: ${!link.existsSync()}');
print('target kept: ${target.readAsStringSync()}');
tmp.deleteSync(recursive: true);
}link gone: true target kept: keep me
Stream<FileSystemEvent> watch({int events = FileSystemEvent.all, bool recursive = false})Start watching the FileSystemEntity for changes.
The implementation uses platform-dependent event-based APIs for receiving file-system notifications, thus behavior depends on the platform.
Windows: UsesReadDirectoryChangesW. The implementation only supports watching directories. Recursive watching is supported.Linux: Usesinotify. The implementation supports watching both files and directories. Recursive watching is not supported. Note: When watching files directly, delete events might not happen as expected.OS X: Uses the File System Events API. The implementation supports watching both files and directories. Recursive watching is supported. This API has several limitations:
- Changes that occurred shortly before the
watchmethod was called may still appear in theStream. - Changes that occur in a short period of time may arrive out-of-order.
- Multiple changes made in a single directory may be coalesced into a single
FileSystemEvent.
The system will start listening for events once the returned Stream is being listened to, not when the call to watch is issued.
The returned value is an endless broadcast Stream, that only stops when one of the following happens:
- The
Streamis canceled, e.g. by callingcancelon theStreamSubscription. - The
FileSystemEntitybeing watched is deleted. - System Watcher exits unexpectedly. e.g. On
Windowsthis happens when buffer that receive events fromReadDirectoryChangesWoverflows.
Use events to specify what events to listen for. The constants in FileSystemEvent can be or'ed together to mix events. Default is FileSystemEvent.all.
A move event may be reported as separate delete and create events.
import 'raya:io';
void main() {
// watch() reports changes as a stream of FileSystemEvents. Event types are bit flags:
print('create: ${FileSystemEvent.create}');
print('modify: ${FileSystemEvent.modify}');
print('delete: ${FileSystemEvent.delete}');
print('move: ${FileSystemEvent.move}');
print('all: ${FileSystemEvent.all}');
print('watch only creates and deletes: mask ${FileSystemEvent.create | FileSystemEvent.delete}');
}create: 1 modify: 2 delete: 4 move: 8 all: 15 watch only creates and deletes: mask 5
FileSystemEvent
sealed class FileSystemEvent
Base event class emitted by FileSystemEntity.watch.
Static
static const int create = 1 << 0Bitfield for FileSystemEntity.watch, to enable FileSystemCreateEvents.
static const int modify = 1 << 1Bitfield for FileSystemEntity.watch, to enable FileSystemModifyEvents.
static const int delete = 1 << 2Bitfield for FileSystemEntity.watch, to enable FileSystemDeleteEvents.
static const int move = 1 << 3Bitfield for FileSystemEntity.watch, to enable FileSystemMoveEvents.
static const int all = create | modify | delete | moveBitfield for FileSystemEntity.watch, for enabling all of create, modify, delete and move.
Properties
final String pathThe path that triggered the event.
Depending on the platform and the FileSystemEntity, the path may be relative.
final bool isDirectoryWhether the event target is a directory.
The value will always be false for FileSystemDeleteEvent.
On Windows isDirectory is computed by checking the file system entity type after the event, which means it can be incorrect. It can be incorrectly false for a directory create, modify or move event if that directory was deleted soon after the event occurred. And, it can be incorrectly true for a newly created link to a directory.
final class FileSystemCreateEvent extends FileSystemEvent
File system event for newly created file system objects.
Constructors
FileSystemCreateEvent(String path, bool isDirectory)Constructs a new FileSystemCreateEvent.
import 'raya:io';
void main() {
final e = FileSystemCreateEvent('logs/today.txt', false);
print('type ${e.type == FileSystemEvent.create}, path ${e.path}, isDirectory ${e.isDirectory}');
}type true, path logs/today.txt, isDirectory false
Methods
String toString()import 'raya:io';
void main() {
print(FileSystemCreateEvent('build', true));
}FileSystemCreateEvent('build', isDirectory=true)final class FileSystemModifyEvent extends FileSystemEvent
File system event for modifications of file system objects.
Constructors
FileSystemModifyEvent(String path, bool isDirectory, this.contentChanged)Constructs a new FileSystemModifyEvent.
import 'raya:io';
void main() {
final e = FileSystemModifyEvent('notes.txt', false, true);
print('contentChanged: ${e.contentChanged}, type is modify: ${e.type == FileSystemEvent.modify}');
}contentChanged: true, type is modify: true
Properties
final bool contentChangedIf the content was changed and not only the attributes, contentChanged is true.
Methods
String toString()import 'raya:io';
void main() {
print(FileSystemModifyEvent('notes.txt', false, false));
}FileSystemModifyEvent('notes.txt', isDirectory=false, contentChanged=false)final class FileSystemDeleteEvent extends FileSystemEvent
File system event for deletion of file system objects.
Constructors
FileSystemDeleteEvent(String path, bool isDirectory)Constructs a new FileSystemDeleteEvent.
import 'raya:io';
void main() {
final e = FileSystemDeleteEvent('tmp/cache', true);
print('deleted ${e.path}, directory: ${e.isDirectory}');
}deleted tmp/cache, directory: false
Properties
bool get isDirectoryWhether the file system object was a directory.
The value will always be false for FileSystemDeleteEvent.
Methods
String toString()import 'raya:io';
void main() {
print(FileSystemDeleteEvent('old.log', false));
}FileSystemDeleteEvent('old.log')FileSystemMoveEvent
final class FileSystemMoveEvent extends FileSystemEvent
File system event for moving of file system objects.
Constructors
FileSystemMoveEvent(String path, bool isDirectory, this.destination)Constructs a new FileSystemMoveEvent.
import 'raya:io';
void main() {
final e = FileSystemMoveEvent('draft.md', false, 'final.md');
print('moved ${e.path} -> ${e.destination}');
}moved draft.md -> final.md
Properties
final String? destinationThe destination path of the file being moved.
The destination is null if the underlying implementation is unable to identify the destination of the moved file.
The source path is available as path.
Methods
String toString()import 'raya:io';
void main() {
print(FileSystemMoveEvent('a.txt', false, 'b.txt'));
}FileSystemMoveEvent('a.txt', isDirectory=false, destination=b.txt)IOSink
abstract interface class IOSink implements StreamSink<List<int>>, StringSink
A combined byte and text output.
An IOSink combines a StreamSink of bytes with a StringSink, and allows easy output of both bytes and text.
An IOSink is intended for writing bytes. Strings written through write or writeCharCode will be converted to bytes using encoding. Integer data added using add or addStream will be treated as byte data, and will be truncated to unsigned 8-bit values as by using int.toUnsigned. No guarantees are given for when such a conversion happens, since it depends on the implementation behind the sink.
Writing text (write) and adding bytes (add) may be interleaved freely.
While a stream is being added using addStream, any further attempts to add or write to the IOSink will fail until the addStream completes.
It is an error to add data to the IOSink after the sink is closed.
Constructors
factory IOSink(StreamConsumer<List<int>> target, {Encoding encoding = utf8})Create an IOSink that outputs to a target StreamConsumer of bytes.
Text written to StreamSink methods is encoded to bytes using encoding before being output on target.
import 'raya:io';
import 'raya:async';
import 'raya:convert';
Future<void> main() async {
final collected = StreamController<List<int>>();
final sink = IOSink(collected.sink, encoding: latin1);
sink.write('café');
final bytes = collected.stream.expand((c) => c).toList();
await sink.close();
print('latin1 bytes: ${await bytes}');
}latin1 bytes: [99, 97, 102, 233]
Properties
late Encoding encodingThe Encoding used when writing strings.
Depending on the underlying consumer, this property might be mutable.
Future get doneA future that will complete when the consumer closes, or when an error occurs.
This future is identical to the future returned by close.
Methods
void add(List<int> data)Adds byte data to the target consumer, ignoring encoding.
The encoding does not apply to this method, and the data list is passed directly to the target consumer as a stream event.
This method must not be called when a stream is currently being added using addStream.
This operation is non-blocking. See flush or done for how to get any errors generated by this call.
The data list should not be modified after it has been passed to add because it is not defined whether the target consumer will receive the list in the original or modified state.
Individual values in data which are not in the range 0.. 255 will be truncated to their low eight bits, as if by int.toUnsigned, before being used.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final f = File('${tmp.path}/a.bin');
final sink = f.openWrite();
sink.add([1, 2, 3]);
sink.add([4]);
await sink.close();
print('file bytes: ${f.readAsBytesSync()}');
tmp.deleteSync(recursive: true);
}file bytes: [1, 2, 3, 4]
void write(Object? object)Converts object to a String by invoking Object.toString and adds the encoding of the result to the target consumer.
This operation is non-blocking. See flush or done for how to get any errors generated by this call.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final f = File('${tmp.path}/a.txt');
final sink = f.openWrite();
sink.write('n = ');
sink.write(42);
sink.write(', ok = ');
sink.write(true);
await sink.close();
print(f.readAsStringSync());
tmp.deleteSync(recursive: true);
}n = 42, ok = true
void writeAll(Iterable objects, [String separator = ""])Iterates over the given objects and writes them in sequence.
If separator is provided, a write with the separator is performed between any two elements of objects.
This operation is non-blocking. See flush or done for how to get any errors generated by this call.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final f = File('${tmp.path}/row.csv');
final sink = f.openWrite();
sink.writeAll(['id', 'name', 'score'], ',');
sink.write('\n');
sink.writeAll([1, 'Ada', 99.5], ',');
await sink.close();
print(f.readAsStringSync());
tmp.deleteSync(recursive: true);
}id,name,score 1,Ada,99.5
void writeln([Object? object = ""])Converts object to a String by invoking Object.toString and writes the result to this, followed by a newline.
This operation is non-blocking. See flush or done for how to get any errors generated by this call.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final f = File('${tmp.path}/a.txt');
final sink = f.openWrite()
..writeln('first')
..writeln()
..writeln('third');
await sink.close();
print(f.readAsLinesSync());
tmp.deleteSync(recursive: true);
}[first, , third]
void writeCharCode(int charCode)Writes the character of charCode.
This method is equivalent to write(String.fromCharCode(charCode)).
This operation is non-blocking. See flush or done for how to get any errors generated by this call.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final f = File('${tmp.path}/a.txt');
final sink = f.openWrite();
for (final c in [0x52, 0x61, 0x79, 0x61, 0x2713]) {
sink.writeCharCode(c);
}
await sink.close();
print('${f.readAsStringSync()} (${f.lengthSync()} bytes in UTF-8)');
tmp.deleteSync(recursive: true);
}Raya✓ (7 bytes in UTF-8)
void addError(error, [StackTrace? stackTrace])Passes the error to the target consumer as an error event.
This method must not be called when a stream is currently being added using addStream.
This operation is non-blocking. See flush or done for how to get any errors generated by this call.
import 'raya:io';
import 'raya:async';
Future<void> main() async {
final target = StreamController<List<int>>();
final sink = IOSink(target.sink);
final errors = target.stream.handleError((e) => print('consumer got error: $e')).drain<void>();
sink.add([1]);
sink.addError(StateError('upstream failed'));
await sink.close();
await errors;
}consumer got error: Bad state: upstream failed
Future addStream(Stream<List<int>> stream)Adds all elements of the given stream.
Returns a Future that completes when all elements of the given stream have been added.
If the stream contains an error, the addStream ends at the error, and the returned future completes with that error.
This method must not be called when a stream is currently being added using this method.
Individual values in the lists emitted by stream which are not in the range 0.. 255 will be truncated to their low eight bits, as if by int.toUnsigned, before being used.
import 'raya:io';
import 'raya:convert';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final f = File('${tmp.path}/a.txt');
final sink = f.openWrite();
await sink.addStream(Stream.fromIterable(['alpha ', 'beta ', 'gamma']).transform(utf8.encoder));
sink.write('!');
await sink.close();
print(f.readAsStringSync());
tmp.deleteSync(recursive: true);
}alpha beta gamma!
Future flush()Returns a Future that completes once all buffered data is accepted by the underlying StreamConsumer.
This method must not be called while an addStream is incomplete.
NOTE: This is not necessarily the same as the data being flushed by the operating system.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final f = File('${tmp.path}/a.txt');
final sink = f.openWrite();
sink.write('partial');
await sink.flush();
print('on disk after flush: ${f.readAsStringSync()}');
sink.write(' and more');
await sink.close();
print('after close: ${f.readAsStringSync()}');
tmp.deleteSync(recursive: true);
}on disk after flush: partial after close: partial and more
Future close()Close the target consumer.
NOTE: Writes to the IOSink may be buffered, and may not be flushed by a call to close. To flush all buffered writes, call flush before calling close.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final sink = File('${tmp.path}/a.txt').openWrite();
sink.write('done');
await sink.close();
try {
sink.write('late');
} on StateError catch (e) {
print('write after close: ${e.message}');
}
tmp.deleteSync(recursive: true);
}write after close: StreamSink is closed
Link
abstract interface class Link implements FileSystemEntity
References to filesystem links.
Constructors
factory Link(String path)Creates a Link object.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
File('${tmp.path}/real.txt').writeAsStringSync('the real file');
final link = Link('${tmp.path}/alias.txt')..createSync('real.txt');
print('link target: ${link.targetSync()}');
print('read through link: ${File(link.path).readAsStringSync()}');
tmp.deleteSync(recursive: true);
}link target: real.txt read through link: the real file
factory Link.fromRawPath(Uint8List rawPath)import 'raya:io';
import 'raya:convert';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final link = Link.fromRawPath(utf8.encode('${tmp.path}/café-link'));
link.createSync('target');
print('name: ${link.path.split('/').last}, target: ${link.targetSync()}');
tmp.deleteSync(recursive: true);
}name: café-link, target: target
factory Link.fromUri(Uri uri)Creates a Link object.
If path is a relative path, it will be interpreted relative to the current working directory (see Directory.current), when used.
If path is an absolute path, it will be immune to changes to the current working directory.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final link = Link.fromUri(Uri.directory(tmp.path).resolve('latest'));
link.createSync('v2');
print('link name: ${link.uri.pathSegments.last}, target: ${link.targetSync()}');
tmp.deleteSync(recursive: true);
}link name: latest, target: v2
Properties
Link get absoluteMethods
Future<Link> create(String target, {bool recursive = false})Creates a symbolic link in the file system.
The created link will point to the path at target, whether that path exists or not.
Returns a Future<Link> that completes with the link when it has been created. If the link path already exists, the future will complete with an error.
If recursive is false, the default, the link is created only if all directories in its path exist. If recursive is true, all non-existing parent paths are created first. The directories in the path of target are not affected, unless they are also in path.
On the Windows platform, this call will create a true symbolic link instead of a junction. Windows treats links to files and links to directories as different and non-interchangable kinds of links. Each link is either a file-link or a directory-link, and the type is chosen when the link is created, and the link then counts as either a file or directory for most purposes. Different Win32 API calls are used to manipulate each. For example, the DeleteFile function is used to delete links to files, and RemoveDirectory must be used to delete links to directories.
The created Windows symbolic link will match the type of the target, if target exists, otherwise a file-link is created. The type of the created link will not change if target is later replaced by something of a different type, but then the link will not be resolvable by resolveSymbolicLinks.
In order to create a symbolic link on Windows, Raya must be run in Administrator mode or the system must have Developer Mode enabled, otherwise a FileSystemException will be raised with ERROR_PRIVILEGE_NOT_HELD set as the errno when this call is made.
On other platforms, the POSIX symlink call is used to make a symbolic link containing the string target. If target is a relative path, it will be interpreted relative to the directory containing the link.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final link = await Link('${tmp.path}/a/b/link').create('../../target', recursive: true);
print('created with parent directories: ${link.existsSync()}, target ${await link.target()}');
tmp.deleteSync(recursive: true);
}created with parent directories: true, target ../../target
void createSync(String target, {bool recursive = false})Creates a symbolic link in the file system.
The created link will point to the path at target, whether that path exists or not.
If the link path already exists, an exception will be thrown.
If recursive is false, the default, the link is created only if all directories in its path exist. If recursive is true, all non-existing parent paths are created first. The directories in the path of target are not affected, unless they are also in path.
On the Windows platform, this call will create a true symbolic link instead of a junction. Windows treats links to files and links to directories as different and non-interchangable kinds of links. Each link is either a file-link or a directory-link, and the type is chosen when the link is created, and the link then counts as either a file or directory for most purposes. Different Win32 API calls are used to manipulate each. For example, the DeleteFile function is used to delete links to files, and RemoveDirectory must be used to delete links to directories.
The created Windows symbolic link will match the type of the target, if target exists, otherwise a file-link is created. The type of the created link will not change if target is later replaced by something of a different type, but then the link will not be resolvable by resolveSymbolicLinks.
In order to create a symbolic link on Windows, Raya must be run in Administrator mode or the system must have Developer Mode enabled, otherwise a FileSystemException will be raised with ERROR_PRIVILEGE_NOT_HELD set as the errno when this call is made.
On other platforms, the POSIX symlink call is used to make a symbolic link containing the string target. If target is a relative path, it will be interpreted relative to the directory containing the link.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
Directory('${tmp.path}/release-1.2').createSync();
final current = Link('${tmp.path}/current')..createSync('release-1.2');
print('current -> ${current.targetSync()}, is a link: ${FileSystemEntity.isLinkSync(current.path)}');
tmp.deleteSync(recursive: true);
}current -> release-1.2, is a link: true
void updateSync(String target)Synchronously updates an existing link.
Deletes the existing link at path and uses createSync to create a new link to target. Throws PathNotFoundException if the original link does not exist or any FileSystemException that deleteSync or createSync can throw.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final current = Link('${tmp.path}/current')..createSync('v1');
print('before: ${current.targetSync()}');
current.updateSync('v2');
print('after updateSync: ${current.targetSync()}');
tmp.deleteSync(recursive: true);
}before: v1 after updateSync: v2
Future<Link> update(String target)Updates an existing link.
Deletes the existing link at path and creates a new link to target, using create.
Returns a future which completes with this Link if successful, and with a PathNotFoundException if there is no existing link at path, or with any FileSystemException that delete or create can throw.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final link = Link('${tmp.path}/stable')..createSync('build-41');
await link.update('build-42');
print('stable -> ${await link.target()}');
tmp.deleteSync(recursive: true);
}stable -> build-42
Future<String> resolveSymbolicLinks()import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final real = File('${tmp.path}/data.txt')..createSync();
final hop1 = Link('${tmp.path}/hop1')..createSync('data.txt');
Link('${tmp.path}/hop2').createSync('hop1');
final resolved = await Link('${tmp.path}/hop2').resolveSymbolicLinks();
print('two hops resolve to: ${resolved.split('/').last}');
print('same as the file: ${resolved == real.resolveSymbolicLinksSync()} (${hop1.targetSync()})');
tmp.deleteSync(recursive: true);
}two hops resolve to: data.txt same as the file: true (data.txt)
String resolveSymbolicLinksSync()import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
Directory('${tmp.path}/real').createSync();
final link = Link('${tmp.path}/alias')..createSync('real');
print('resolves to the folder named: ${link.resolveSymbolicLinksSync().split('/').last}');
tmp.deleteSync(recursive: true);
}resolves to the folder named: real
Future<Link> rename(String newPath)Renames this link.
Returns a Future<Link> that completes with a Link for the renamed link.
If newPath identifies an existing file or link, that entity is removed first. If newPath identifies an existing directory then the future completes with a FileSystemException.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final link = Link('${tmp.path}/old')..createSync('target');
final moved = await link.rename('${tmp.path}/new');
print('renamed: ${moved.path.split('/').last} -> ${moved.targetSync()}, old exists: ${link.existsSync()}');
tmp.deleteSync(recursive: true);
}renamed: new -> target, old exists: false
Link renameSync(String newPath)Synchronously renames this link.
Returns a Link instance for the renamed link.
If newPath identifies an existing file or link, that entity is removed first. If newPath identifies an existing directory then FileSystemException is thrown.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final link = Link('${tmp.path}/a')..createSync('t');
final b = link.renameSync('${tmp.path}/b');
print('names now: ${tmp.listSync().map((e) => e.path.split('/').last).toList()}, target ${b.targetSync()}');
tmp.deleteSync(recursive: true);
}names now: [b], target t
Future<FileSystemEntity> delete({bool recursive = false})Deletes this Link.
If recursive is false:
- If
pathcorresponds to a link then that path is deleted. Otherwise,deletecompletes with aFileSystemException.
If recursive is true:
- The
FileSystemEntityatpathis deleted regardless of type. Ifpathcorresponds to a file or link, then that file or link is deleted. Ifpathcorresponds to a directory, then it and all sub-directories and files in those directories are deleted. Links are not followed when deleting recursively. Only the link is deleted, not its target. This behavior allowsdeleteto be used to unconditionally delete any file system object.
If this Link cannot be deleted, then delete completes with a FileSystemException.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final real = File('${tmp.path}/real.txt')..writeAsStringSync('keep me');
final link = Link('${tmp.path}/alias')..createSync('real.txt');
await link.delete();
print('link gone: ${!link.existsSync()}, target kept: ${real.readAsStringSync()}');
tmp.deleteSync(recursive: true);
}link gone: true, target kept: keep me
void deleteSync({bool recursive = false})Synchronously deletes this Link.
If recursive is false:
- If
pathcorresponds to a link then that path is deleted. Otherwise,deletethrows aFileSystemException.
If recursive is true:
- The
FileSystemEntityatpathis deleted regardless of type. Ifpathcorresponds to a file or link, then that file or link is deleted. Ifpathcorresponds to a directory, then it and all sub-directories and files in those directories are deleted. Links are not followed when deleting recursively. Only the link is deleted, not its target. This behavior allowsdeleteto be used to unconditionally delete any file system object.
If this Link cannot be deleted, then delete throws a FileSystemException.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final dangling = Link('${tmp.path}/broken')..createSync('nowhere');
print('dangling link exists as a link: ${FileSystemEntity.isLinkSync(dangling.path)}');
dangling.deleteSync();
print('after deleteSync: ${FileSystemEntity.typeSync(dangling.path, followLinks: false)}');
tmp.deleteSync(recursive: true);
}dangling link exists as a link: true after deleteSync: notFound
Future<String> target()Gets the target of the link.
Returns a future that completes with the path to the target.
If the returned target is a relative path, it is relative to the directory containing the link.
If the link does not exist, or is not a link, the future completes with a FileSystemException.
import 'raya:io';
Future<void> main() async {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final link = Link('${tmp.path}/docs')..createSync('../shared/docs');
print('target is stored as written: ${await link.target()}');
tmp.deleteSync(recursive: true);
}target is stored as written: ../shared/docs
String targetSync()Synchronously gets the target of the link.
Returns the path to the target.
If the returned target is a relative path, it is relative to the directory containing the link.
If the link does not exist, or is not a link, throws a FileSystemException.
import 'raya:io';
void main() {
final tmp = Directory.systemTemp.createTempSync('raya_ex_');
final link = Link('${tmp.path}/l')..createSync('a/b/c.txt');
print('targetSync: ${link.targetSync()}');
try {
Link('${tmp.path}/missing').targetSync();
} on FileSystemException {
print('not a link: FileSystemException');
}
tmp.deleteSync(recursive: true);
}targetSync: a/b/c.txt not a link: FileSystemException
IOOverrides
abstract base class IOOverrides
Facilities for overriding various APIs of raya:io with mock implementations.
This abstract base class should be extended with overrides for the operations needed to construct mocks. The implementations in this base class default to the actual raya:io implementation. For example:
class MyDirectory implements Directory {
...
// An implementation of the Directory interface
...
}
void main() {
IOOverrides.runZoned(() {
...
// Operations will use MyDirectory instead of raya:io's Directory
// implementation whenever Directory is used.
...
}, createDirectory: (String path) => new MyDirectory(path));
}Static
static IOOverrides? get currentstatic set global(IOOverrides? overrides)The IOOverrides to use in the root Zone.
These are the IOOverrides that will be used in the root Zone, and in Zone's that do not set IOOverrides and whose ancestors up to the root Zone also do not set IOOverrides.
import 'raya:io';
final class FixedTemp extends IOOverrides {
@override
Directory getSystemTempDirectory() => Directory('/sandbox/tmp');
}
void main() {
IOOverrides.global = FixedTemp(); // applies everywhere, not just in a zone
print('systemTemp: ${Directory.systemTemp.path}');
IOOverrides.global = null;
print('restored: ${Directory.systemTemp.path != '/sandbox/tmp'}');
}systemTemp: /sandbox/tmp restored: true
static R runZoned<R>(R body(), {Directory Function(String)? createDirectory, Directory Function()? getCurrentDirectory, void Function(String)? setCurrentDirectory, Directory Function()? getSystemTempDirectory, File Function(String)? createFile, Future<FileStat> Function(String)? stat, FileStat Function(String)? statSync, Future<bool> Function(String, String)? fseIdentical, bool Function(String, String)? fseIdenticalSync, Future<FileSystemEntityType> Function(String, bool)? fseGetType, FileSystemEntityType Function(String, bool)? fseGetTypeSync, Stream<FileSystemEvent> Function(String, int, bool)? fsWatch, bool Function()? fsWatchIsSupported, Link Function(String)? createLink, Future<Socket> Function(dynamic, int, {dynamic sourceAddress, int sourcePort, Duration? timeout})? socketConnect, Future<ConnectionTask<Socket>> Function(dynamic, int, {dynamic sourceAddress, int sourcePort})? socketStartConnect, Future<ServerSocket> Function(dynamic, int, {int backlog, bool v6Only, bool shared})? serverSocketBind, Stdin Function()? stdin, Stdout Function()? stdout, Stdout Function()? stderr, @Since("3.10") Never Function(int)? exit})Runs body in a fresh Zone using the provided overrides.
See the documentation on the corresponding methods of IOOverrides for information about what the optional arguments do.
import 'raya:io';
void main() {
final created = <String>[];
// Build the replacement outside the zone: calling File() inside createFile would recurse.
final virtual = File('/virtual/file');
IOOverrides.runZoned(() {
File('report.txt');
File('data/raw.csv');
print('current dir inside: ${Directory.current.path}');
}, createFile: (path) {
created.add(path);
return virtual;
}, getCurrentDirectory: () => Directory('/virtual'));
print('files requested through the override: $created');
}current dir inside: /virtual files requested through the override: [report.txt, data/raw.csv]
static R runWithIOOverrides<R>(R body(), IOOverrides overrides)Runs body in a fresh Zone using the overrides found in overrides.
Note that overrides should be an instance of a class that extends IOOverrides.
import 'raya:io';
final class ReadOnlyFiles extends IOOverrides {
final opened = <String>[];
@override
File createFile(String path) {
opened.add(path);
return super.createFile(path);
}
}
void main() {
final o = ReadOnlyFiles();
IOOverrides.runWithIOOverrides(() {
File('a.txt');
File('b.txt');
}, o);
print('File objects made in the zone: ${o.opened}');
}File objects made in the zone: [a.txt, b.txt]
Properties
Stdin get stdinThe standard input stream of data read by this program.
When this override is installed, this getter overrides the behavior of the top-level stdin getter.
Stdout get stdoutThe standard output stream of data written by this program.
When this override is installed, this getter overrides the behavior of the top-level stdout getter.
Stdout get stderrThe standard output stream of errors written by this program.
When this override is installed, this getter overrides the behavior of the top-level stderr getter.
Methods
Directory createDirectory(String path)Creates a new Directory object for the given path.
When this override is installed, this function overrides the behavior of new Directory and new Directory.fromUri.
import 'raya:io';
final class Chroot extends IOOverrides {
@override
Directory createDirectory(String path) => super.createDirectory('/jail${path.startsWith('/') ? '' : '/'}$path');
}
void main() {
IOOverrides.runWithIOOverrides(() {
print(Directory('/etc').path);
print(Directory('home/ada').path);
}, Chroot());
}/jail/etc /jail/home/ada
Directory getCurrentDirectory()Returns the current working directory.
When this override is installed, this function overrides the behavior of the static getter Directory.current
import 'raya:io';
final class InProject extends IOOverrides {
@override
Directory getCurrentDirectory() => Directory('/work/project');
}
void main() {
IOOverrides.runWithIOOverrides(() {
print('Directory.current: ${Directory.current.path}');
}, InProject());
}Directory.current: /work/project
void setCurrentDirectory(String path)Sets the current working directory to be path.
When this override is installed, this function overrides the behavior of the setter Directory.current.
import 'raya:io';
final class TrackCd extends IOOverrides {
String cwd = '/';
@override
void setCurrentDirectory(String path) => cwd = path;
@override
Directory getCurrentDirectory() => Directory(cwd);
}
void main() {
IOOverrides.runWithIOOverrides(() {
Directory.current = '/tmp/build';
print('after cd: ${Directory.current.path}');
}, TrackCd());
}after cd: /tmp/build
Directory getSystemTempDirectory()Returns the system temporary directory.
When this override is installed, this function overrides the behavior of Directory.systemTemp.
import 'raya:io';
void main() {
IOOverrides.runZoned(() {
print('systemTemp: ${Directory.systemTemp.path}');
}, getSystemTempDirectory: () => Directory('/ramdisk/tmp'));
}systemTemp: /ramdisk/tmp
File createFile(String path)Creates a new File object for the given path.
When this override is installed, this function overrides the behavior of new File and new File.fromUri.
import 'raya:io';
final class Prefixed extends IOOverrides {
@override
File createFile(String path) => super.createFile('out/$path');
}
void main() {
IOOverrides.runWithIOOverrides(() {
print(File('log.txt').path);
}, Prefixed());
print('outside: ${File('log.txt').path}');
}out/log.txt outside: log.txt
Future<FileStat> stat(String path)Asynchronously returns FileStat information for path.
When this override is installed, this function overrides the behavior of FileStat.stat.
import 'raya:io';
final class AllMissing extends IOOverrides {
@override
Future<FileStat> stat(String path) => super.stat('/definitely/not/here');
}
Future<void> main() async {
await IOOverrides.runWithIOOverrides(() async {
final s = await FileStat.stat('/');
print('stat("/") inside the override: ${s.type}');
}, AllMissing());
}stat("/") inside the override: notFoundFileStat statSync(String path)Returns FileStat information for path.
When this override is installed, this function overrides the behavior of FileStat.statSync.
import 'raya:io';
final class Logged extends IOOverrides {
final paths = <String>[];
@override
FileStat statSync(String path) {
paths.add(path);
return super.statSync(path);
}
}
void main() {
final o = Logged();
IOOverrides.runWithIOOverrides(() => FileStat.statSync('/'), o);
print('statSync calls: ${o.paths}');
}statSync calls: [/]
Future<bool> fseIdentical(String path1, String path2)Asynchronously returns true if path1 and path2 are paths to the same file system object.
When this override is installed, this function overrides the behavior of FileSystemEntity.identical.
import 'raya:io';
final class SameEverything extends IOOverrides {
@override
Future<bool> fseIdentical(String a, String b) async => true;
}
Future<void> main() async {
await IOOverrides.runWithIOOverrides(() async {
print('identical(a, b): ${await FileSystemEntity.identical('a', 'b')}');
}, SameEverything());
}identical(a, b): true
bool fseIdenticalSync(String path1, String path2)Returns true if path1 and path2 are paths to the same file system object.
When this override is installed, this function overrides the behavior of FileSystemEntity.identicalSync.
import 'raya:io';
final class CaseInsensitive extends IOOverrides {
@override
bool fseIdenticalSync(String a, String b) => a.toLowerCase() == b.toLowerCase();
}
void main() {
IOOverrides.runWithIOOverrides(() {
print('README vs readme: ${FileSystemEntity.identicalSync('README', 'readme')}');
}, CaseInsensitive());
}README vs readme: true
Future<FileSystemEntityType> fseGetType(String path, bool followLinks)Asynchronously returns the FileSystemEntityType for path.
When this override is installed, this function overrides the behavior of FileSystemEntity.type.
import 'raya:io';
final class VirtualFs extends IOOverrides {
@override
Future<FileSystemEntityType> fseGetType(String path, bool followLinks) async =>
path.endsWith('/') ? FileSystemEntityType.directory : FileSystemEntityType.file;
}
Future<void> main() async {
await IOOverrides.runWithIOOverrides(() async {
print('docs/: ${await FileSystemEntity.type('docs/')}');
print('a.txt: ${await FileSystemEntity.type('a.txt')}');
}, VirtualFs());
}docs/: directory a.txt: file
FileSystemEntityType fseGetTypeSync(String path, bool followLinks)Returns the FileSystemEntityType for path.
When this override is installed, this function overrides the behavior of FileSystemEntity.typeSync.
import 'raya:io';
final class OnlyDirs extends IOOverrides {
@override
FileSystemEntityType fseGetTypeSync(String path, bool followLinks) => FileSystemEntityType.directory;
}
void main() {
IOOverrides.runWithIOOverrides(() {
print('anything is a directory: ${FileSystemEntity.isDirectorySync('x.txt')}');
}, OnlyDirs());
}anything is a directory: true
Stream<FileSystemEvent> fsWatch(String path, int events, bool recursive)Returns a Stream of FileSystemEvents.
When this override is installed, this function overrides the behavior of FileSystemEntity.watch.
import 'raya:io';
final class FakeWatch extends IOOverrides {
@override
Stream<FileSystemEvent> fsWatch(String path, int events, bool recursive) =>
Stream.fromIterable([FileSystemCreateEvent('$path/new.txt', false)]);
}
Future<void> main() async {
await IOOverrides.runWithIOOverrides(() async {
await for (final e in Directory('/data').watch()) {
print('event: $e');
}
}, FakeWatch());
}event: FileSystemCreateEvent('/data/new.txt', isDirectory=false)bool fsWatchIsSupported()Returns true when FileSystemEntity.watch is supported.
When this override is installed, this function overrides the behavior of FileSystemEntity.isWatchSupported.
import 'raya:io';
final class NoWatch extends IOOverrides {
@override
bool fsWatchIsSupported() => false;
}
void main() {
IOOverrides.runWithIOOverrides(() {
print('isWatchSupported in the zone: ${FileSystemEntity.isWatchSupported}');
}, NoWatch());
}isWatchSupported in the zone: false
Link createLink(String path)Returns a new Link object for the given path.
When this override is installed, this function overrides the behavior of new Link and new Link.fromUri.
import 'raya:io';
final class Links extends IOOverrides {
final made = <String>[];
@override
Link createLink(String path) {
made.add(path);
return super.createLink(path);
}
}
void main() {
final o = Links();
IOOverrides.runWithIOOverrides(() => Link('current'), o);
print('links created: ${o.made}');
}links created: [current]
Future<Socket> socketConnect(host, int port, {sourceAddress, int sourcePort = 0, Duration? timeout})Asynchronously returns a Socket connected to the given host and port.
When this override is installed, this function overrides the behavior of Socket.connect(...).
import 'raya:io';
final class Redirect extends IOOverrides {
final int port;
Redirect(this.port);
@override
Future<Socket> socketConnect(host, int port, {sourceAddress, int sourcePort = 0, Duration? timeout}) =>
super.socketConnect(InternetAddress.loopbackIPv4, this.port);
}
Future<void> main() async {
const t = Duration(seconds: 2);
final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
server.listen((s) => s..write('hello from the local server')..close()..drain<void>());
await IOOverrides.runWithIOOverrides(() async {
final s = await Socket.connect('example.invalid', 80).timeout(t); // goes to localhost instead
print(String.fromCharCodes(await s.expand((c) => c).toList().timeout(t)));
s.destroy();
}, Redirect(server.port));
await server.close();
}hello from the local server
Future<ConnectionTask<Socket>> socketStartConnect(host, int port, {sourceAddress, int sourcePort = 0})Asynchronously returns a ConnectionTask that connects to the given host and port when successful.
When this override is installed, this function overrides the behavior of Socket.startConnect(...).
import 'raya:io';
final class Count extends IOOverrides {
var starts = 0;
@override
Future<ConnectionTask<Socket>> socketStartConnect(host, int port, {sourceAddress, int sourcePort = 0}) {
starts++;
return super.socketStartConnect(host, port);
}
}
Future<void> main() async {
final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
server.listen((s) => s.destroy());
final o = Count();
await IOOverrides.runWithIOOverrides(() async {
final task = await Socket.startConnect(InternetAddress.loopbackIPv4, server.port);
(await task.socket.timeout(const Duration(seconds: 2))).destroy();
}, o);
print('startConnect calls seen: ${o.starts}');
await server.close();
}startConnect calls seen: 1
Future<ServerSocket> serverSocketBind(address, int port, {int backlog = 0, bool v6Only = false, bool shared = false})Asynchronously returns a ServerSocket that connects to the given address and port when successful.
When this override is installed, this function overrides the behavior of ServerSocket.bind(...).
import 'raya:io';
final class LoopbackOnly extends IOOverrides {
@override
Future<ServerSocket> serverSocketBind(address, int port, {int backlog = 0, bool v6Only = false, bool shared = false}) =>
super.serverSocketBind(InternetAddress.loopbackIPv4, port);
}
Future<void> main() async {
await IOOverrides.runWithIOOverrides(() async {
final s = await ServerSocket.bind(InternetAddress.anyIPv4, 0);
print('asked for any address, bound to: ${s.address.address}');
await s.close();
}, LoopbackOnly());
}asked for any address, bound to: 127.0.0.1
Never exit(int code)Exit the Raya VM process immediately with the given exit code.
When this override is installed, this function overrides the behavior of exit(...).
import 'raya:io';
final class NoExit extends IOOverrides {
@override
Never exit(int code) => throw StateError('exit($code) blocked in tests');
}
void main() {
IOOverrides.runWithIOOverrides(() {
try {
exit(1);
} on StateError catch (e) {
print(e.message);
}
}, NoExit());
}exit(1) blocked in tests
Platform
abstract final class Platform
Information about the environment in which the current program is running.
Platform provides information such as the operating system, the hostname of the computer, the value of environment variables, the path to the running program, and other global properties of the program being run.
Get the URI of the current Raya script
Use the script getter to get the URI to the currently running Raya script.
import 'raya:io' show Platform;
void main() {
// Get the URI of the script being run.
var uri = Platform.script;
// Convert the URI to a path.
var path = uri.toFilePath();
}
Get the value of an environment variable
The environment getter returns a the names and values of environment variables in a Map that contains key-value pairs of strings. The Map is unmodifiable. This sample shows how to get the value of the PATH environment variable.
import 'raya:io' show Platform;
void main() {
Map<String, String> envVars = Platform.environment;
print(envVars['PATH']);
}
Determine the OS
You can get the name of the operating system as a string with the operatingSystem getter. You can also use one of the static boolean getters: isMacOS, isLinux, isWindows, etc.
import 'raya:io' show Platform;
void main() {
// Get the operating system as a string.
String os = Platform.operatingSystem;
// Or, use a predicate getter.
if (Platform.isMacOS) {
print('is a Mac');
} else {
print('is not a Mac');
}
}Static
static final numberOfProcessorsThe number of individual execution units of the machine.
static final pathSeparatorThe path separator used by the operating system to separate components in file paths.
static final operatingSystemA string representing the operating system or platform.
Possible values include:
- "android"
- "fuchsia"
- "ios"
- "linux"
- "macos"
- "windows"
Note that this list may change over time so platform-specific logic should be guarded by the appropriate Boolean getter e.g. isMacOS.
static final operatingSystemVersionA string representing the version of the operating system or platform.
The format of this string will vary by operating system, platform and version and is not suitable for parsing. For example: "Linux 5.11.0-1018-gcp #20~20.04.2-Ubuntu SMP Fri Sep 3 01:01:37 UTC 2021" "Version 14.5 (Build 18E182)" '"Windows 10 Pro" 10.0 (Build 19043)'
static final localHostname