File abstract interface#
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 'dart:async';
import 'dart: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 'dart:io';
import 'dart:convert';
import 'dart: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 'dart: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 'dart: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 'dart: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.
Other resources#
-
The Files and directories section of the library tour.
-
Write Command-Line Apps, a tutorial about writing command-line apps, includes information about files and directories.
Implemented types
Constructors#
File() factory#
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.
Implementation
@pragma("vm:entry-point")
factory File(String path) {
final IOOverrides? overrides = IOOverrides.current;
if (overrides == null) {
return _File(path);
}
return overrides.createFile(path);
}
File.fromRawPath() factory#
Creates a File object from a raw path.
A raw path is a sequence of bytes, as paths are represented by the OS.
Implementation
@pragma("vm:entry-point")
factory File.fromRawPath(Uint8List rawPath) {
// TODO(bkonyi): Handle overrides.
return _File.fromRawPath(rawPath);
}
File.fromUri() factory#
Create a File object from a URI.
If uri cannot reference a file this throws UnsupportedError.
Implementation
factory File.fromUri(Uri uri) => File(uri.toFilePath());
Properties#
absolute no setter override#
A File with the absolute path of path.
The absolute path is computed by prefixing a relative path with the current working directory, or returning an absolute path unchanged.
Implementation
File get absolute;
hashCode no setter inherited#
The hash code for this object.
A hash code is a single integer which represents the state of the object that affects operator == comparisons.
All objects have hash codes. The default hash code implemented by Object represents only the identity of the object, the same way as the default operator == implementation only considers objects equal if they are identical (see identityHashCode).
If operator == is overridden to use the object state instead, the hash code must also be changed to represent that state, otherwise the object cannot be used in hash based data structures like the default Set and Map implementations.
Hash codes must be the same for objects that are equal to each other according to operator ==. The hash code of an object should only change if the object changes in a way that affects equality. There are no further requirements for the hash codes. They need not be consistent between executions of the same program and there are no distribution guarantees.
Objects that are not equal are allowed to have the same hash code. It is even technically allowed that all instances have the same hash code, but if clashes happen too often, it may reduce the efficiency of hash-based data structures like HashSet or HashMap.
If a subclass overrides hashCode, it should override the operator == operator as well to maintain consistency.
Inherited from Object.
Implementation
external int get hashCode;
isAbsolute no setter inherited#
Whether 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.
Inherited from FileSystemEntity.
Implementation
bool get isAbsolute => _isAbsolute(path);
parent no setter inherited#
The parent directory of this entity.
Inherited from FileSystemEntity.
Implementation
Directory get parent => new Directory(parentOf(path));
path no setter override#
Get the path of the file.
Implementation
String get path;
runtimeType no setter inherited#
A representation of the runtime type of the object.
Inherited from Object.
Implementation
external Type get runtimeType;
uri no setter inherited#
A Uri representing the file system entity's location.
The returned URI's scheme is always "file" if the entity's path is absolute, otherwise the scheme will be empty and the URI relative.
Inherited from FileSystemEntity.
Implementation
Uri get uri => new Uri.file(path);
Methods#
copy()#
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.
Implementation
Future<File> copy(String newPath);
copySync()#
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.
Implementation
File copySync(String newPath);
create()#
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.
Implementation
Future<File> create({bool recursive = false, bool exclusive = false});
createSync()#
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.
Implementation
void createSync({bool recursive = false, bool exclusive = false});
delete() override#
Deletes this File.
If recursive is false:
- If path corresponds to a regular file, named pipe or socket, then that path is deleted. If path corresponds to a link, and that link resolves to a file, then the link at path will be deleted. In all other cases, delete completes with a FileSystemException.
If recursive is true:
- The FileSystemEntity at path is deleted regardless of type. If path corresponds to a file or link, then that file or link is deleted. If path corresponds 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 allows delete to be used to unconditionally delete any file system object.
If this File cannot be deleted, then delete completes with a FileSystemException.
Implementation
Future<FileSystemEntity> delete({bool recursive = false});
deleteSync() override#
Synchronously deletes this File.
If recursive is false:
- If path corresponds to a regular file, named pipe or socket, then that path is deleted. If path corresponds to a link, and that link resolves to a file, then the link at path will be deleted. In all other cases, delete throws a FileSystemException.
If recursive is true:
- The FileSystemEntity at path is deleted regardless of type. If path corresponds to a file or link, then that file or link is deleted. If path corresponds 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 allows delete to be used to unconditionally delete any file system object.
If this File cannot be deleted, then delete throws a FileSystemException.
Implementation
void deleteSync({bool recursive = false});
exists() inherited#
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.
Inherited from FileSystemEntity.
Implementation
Future<bool> exists();
existsSync() inherited#
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.
Inherited from FileSystemEntity.
Implementation
bool existsSync();
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.
Implementation
Future<DateTime> lastAccessed();
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.
Implementation
DateTime lastAccessedSync();
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.
Implementation
Future<DateTime> lastModified();
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.
Implementation
DateTime lastModifiedSync();
length()#
The length of the file.
Returns a Future<int> that completes with the length in bytes.
Implementation
Future<int> length();
lengthSync()#
The length of the file provided synchronously.
Throws a FileSystemException if the operation fails.
Implementation
int lengthSync();
noSuchMethod() inherited#
Invoked when a nonexistent method or property is accessed.
A dynamic member invocation can attempt to call a member which doesn't exist on the receiving object. Example:
dynamic object = 1;
object.add(42); // Statically allowed, run-time error
This invalid code will invoke the noSuchMethod method
of the integer 1 with an Invocation
representing the
.add(42) call and arguments (which then throws).
Classes can override noSuchMethod to provide custom behavior for such invalid dynamic invocations.
A class with a non-default noSuchMethod invocation can also omit implementations for members of its interface. Example:
class MockList<T> implements List<T> {
noSuchMethod(Invocation invocation) {
log(invocation);
super.noSuchMethod(invocation); // Will throw.
}
}
void main() {
MockList().add(42);
}
This code has no compile-time warnings or errors even though
the MockList class has no concrete implementation of
any of the List interface methods.
Calls to List methods are forwarded to noSuchMethod,
so this code will log an invocation similar to
Invocation.method(#add, [42])
and then throw.
If a value is returned from noSuchMethod,
it becomes the result of the original invocation.
If the value is not of a type that can be returned by the original
invocation, a type error occurs at the invocation.
The default behavior is to throw a NoSuchMethodError.
Inherited from Object.
Implementation
@pragma("vm:entry-point")
@pragma("wasm:entry-point")
external dynamic noSuchMethod(Invocation invocation);
open()#
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 as FileMode.write except that the file is not truncated.
Throws a FileSystemException if the operation fails.
Implementation
Future<RandomAccessFile> open({FileMode mode = FileMode.read});
openRead()#
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);
}
Implementation
Stream<List<int>> openRead([int? start, int? end]);
openSync()#
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.
Implementation
RandomAccessFile openSync({FileMode mode = FileMode.read});
openWrite()#
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.
});
Implementation
IOSink openWrite({FileMode mode = FileMode.write, Encoding encoding = utf8});
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.
Implementation
Future<Uint8List> readAsBytes();
readAsBytesSync()#
Synchronously reads the entire file contents as a list of bytes.
Throws a FileSystemException if the operation fails.
Implementation
Uint8List readAsBytesSync();
readAsLines()#
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.
Implementation
Future<List<String>> readAsLines({Encoding encoding = utf8});
readAsLinesSync()#
Synchronously reads the entire file contents as lines of text using the given Encoding.
Throws a FileSystemException if the operation fails.
Implementation
List<String> readAsLinesSync({Encoding encoding = utf8});
readAsString()#
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.
Implementation
Future<String> readAsString({Encoding encoding = utf8});
readAsStringSync()#
Synchronously reads the entire file contents as a string using the given Encoding.
Throws a FileSystemException if the operation fails.
Implementation
String readAsStringSync({Encoding encoding = utf8});
rename() override#
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.
Implementation
Future<File> rename(String newPath);
renameSync() override#
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.
Implementation
File renameSync(String newPath);
resolveSymbolicLinks() inherited#
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.
Inherited from FileSystemEntity.
Implementation
Future<String> resolveSymbolicLinks() {
return _File._dispatchWithNamespace(_IOService.fileResolveSymbolicLinks, [
null,
_rawPath,
]).then((response) {
_checkForErrorResponse(response, "Cannot resolve symbolic links", path);
return response as String;
});
}
resolveSymbolicLinksSync() inherited#
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.
Inherited from FileSystemEntity.
Implementation
String resolveSymbolicLinksSync() {
var result = _resolveSymbolicLinks(_Namespace._namespace, _rawPath);
_throwIfError(result, "Cannot resolve symbolic links", path);
return result;
}
setLastAccessed()#
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.
Implementation
Future setLastAccessed(DateTime time);
setLastAccessedSync()#
Synchronously modifies the time the file was last accessed.
Throws a FileSystemException if the time cannot be set.
Implementation
void setLastAccessedSync(DateTime time);
setLastModified()#
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.
Implementation
Future setLastModified(DateTime time);
setLastModifiedSync()#
Synchronously modifies the time the file was last modified.
If the attributes cannot be set, throws a FileSystemException.
Implementation
void setLastModifiedSync(DateTime time);
stat() inherited#
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.
Inherited from FileSystemEntity.
Implementation
Future<FileStat> stat() => FileStat.stat(path);
statSync() inherited#
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.
Inherited from FileSystemEntity.
Implementation
FileStat statSync() => FileStat.statSync(path);
toString() inherited#
A string representation of this object.
Some classes have a default textual representation,
often paired with a static parse function (like int.parse).
These classes will provide the textual representation as
their string representation.
Other classes have no meaningful textual representation
that a program will care about.
Such classes will typically override toString to provide
useful information when inspecting the object,
mainly for debugging or logging.
Inherited from Object.
Implementation
external String toString();
watch() inherited#
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 watch method was called may still appear in the Stream.
- 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 Stream is canceled, e.g. by calling
cancelon the StreamSubscription. - The FileSystemEntity being 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.
Inherited from FileSystemEntity.
Implementation
Stream<FileSystemEvent> watch({
int events = FileSystemEvent.all,
bool recursive = false,
}) {
// FIXME(bkonyi): find a way to do this using the raw path.
final String trimmedPath = _trimTrailingPathSeparators(path);
final IOOverrides? overrides = IOOverrides.current;
if (overrides == null) {
return _FileSystemWatcher._watch(trimmedPath, events, recursive);
}
return overrides.fsWatch(trimmedPath, events, recursive);
}
writeAsBytes()#
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.
Implementation
Future<File> writeAsBytes(
List<int> bytes, {
FileMode mode = FileMode.write,
bool flush = false,
});
writeAsBytesSync()#
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.
Implementation
void writeAsBytesSync(
List<int> bytes, {
FileMode mode = FileMode.write,
bool flush = false,
});
writeAsString()#
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.
Implementation
Future<File> writeAsString(
String contents, {
FileMode mode = FileMode.write,
Encoding encoding = utf8,
bool flush = false,
});
writeAsStringSync()#
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.
Implementation
void writeAsStringSync(
String contents, {
FileMode mode = FileMode.write,
Encoding encoding = utf8,
bool flush = false,
});
Operators#
operator ==() inherited#
The equality operator.
The default behavior for all Objects is to return true if and
only if this object and other are the same object.
Override this method to specify a different equality relation on a class. The overriding method must still be an equivalence relation. That is, it must be:
Total: It must return a boolean for all arguments. It should never throw.
Reflexive: For all objects
o,o == omust be true.-
Symmetric: For all objects
o1ando2,o1 == o2ando2 == o1must either both be true, or both be false. -
Transitive: For all objects
o1,o2, ando3, ifo1 == o2ando2 == o3are true, theno1 == o3must be true.
The method should also be consistent over time, so whether two objects are equal should only change if at least one of the objects was modified.
If a subclass overrides the equality operator, it should override the hashCode method as well to maintain consistency.
Inherited from Object.
Implementation
external bool operator ==(Object other);