Appearance
File abstract interface
abstract interface class File implements FileSystemEntityA 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.
dart
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:
dart
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.
dart
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:
dart
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.
dart
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.
dart
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
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.
Implementation
dart
@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
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.
Implementation
dart
@pragma("vm:entry-point")
factory File.fromRawPath(Uint8List rawPath) {
// TODO(bkonyi): Handle overrides.
return _File.fromRawPath(rawPath);
}File.fromUri() factory
factory File.fromUri(Uri uri)Create a File object from a URI.
If uri cannot reference a file this throws UnsupportedError.
Implementation
dart
factory File.fromUri(Uri uri) => File(uri.toFilePath());Properties
absolute no setter override
File get absoluteA 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
dart
File get absolute;hashCode no setter inherited
int get hashCodeThe 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
dart
external int get hashCode;isAbsolute no setter inherited
bool 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.
Inherited from FileSystemEntity.
Implementation
dart
bool get isAbsolute => _isAbsolute(path);parent no setter inherited
Directory get parentThe parent directory of this entity.
Inherited from FileSystemEntity.
Implementation
dart
Directory get parent => new Directory(parentOf(path));path no setter override
String get pathGet the path of the file.
Implementation
dart
String get path;runtimeType no setter inherited
Type get runtimeTypeA representation of the runtime type of the object.
Inherited from Object.
Implementation
dart
external Type get runtimeType;uri no setter inherited
Uri get uriA 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
dart
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
dart
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
dart
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
dart
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
dart
void createSync({bool recursive = false, bool exclusive = false});delete() override
Future<FileSystemEntity> delete({bool recursive = false})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
dart
Future<FileSystemEntity> delete({bool recursive = false});deleteSync() override
void deleteSync({bool recursive = false})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
dart
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
dart
Future<bool> exists();existsSync() inherited
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.
Inherited from FileSystemEntity.
Implementation
dart
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
dart
Future<DateTime> lastAccessed();lastAccessedSync()
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.
Implementation
dart
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
dart
Future<DateTime> lastModified();lastModifiedSync()
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.
Implementation
dart
DateTime lastModifiedSync();length()
The length of the file.
Returns a Future<int> that completes with the length in bytes.
Implementation
dart
Future<int> length();lengthSync()
int lengthSync()The length of the file provided synchronously.
Throws a FileSystemException if the operation fails.
Implementation
dart
int lengthSync();noSuchMethod() inherited
dynamic noSuchMethod(Invocation invocation)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:
dart
dynamic object = 1;
object.add(42); // Statically allowed, run-time errorThis 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:
dart
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
dart
@pragma("vm:entry-point")
@pragma("wasm:entry-point")
external dynamic noSuchMethod(Invocation invocation);open()
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 as FileMode.write except that the file is not truncated.
Throws a FileSystemException if the operation fails.
Implementation
dart
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:
dart
// 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
dart
Stream<List<int>> openRead([int? start, int? end]);openSync()
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.
Implementation
dart
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.doneIOSink.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:
dart
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.
dart
final sink = File('/tmp').openWrite(); // Can't write to /tmp
sink.done.catchError((e) {
// Handle the error.
});Implementation
dart
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
dart
Future<Uint8List> readAsBytes();readAsBytesSync()
Uint8List readAsBytesSync()Synchronously reads the entire file contents as a list of bytes.
Throws a FileSystemException if the operation fails.
Implementation
dart
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
dart
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
dart
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
dart
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
dart
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:
dart
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
dart
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:
dart
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
dart
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:
dart
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
dart
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
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:
dart
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
dart
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
dart
Future setLastAccessed(DateTime time);setLastAccessedSync()
void setLastAccessedSync(DateTime time)Synchronously modifies the time the file was last accessed.
Throws a FileSystemException if the time cannot be set.
Implementation
dart
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
dart
Future setLastModified(DateTime time);setLastModifiedSync()
void setLastModifiedSync(DateTime time)Synchronously modifies the time the file was last modified.
If the attributes cannot be set, throws a FileSystemException.
Implementation
dart
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
dart
Future<FileStat> stat() => FileStat.stat(path);statSync() inherited
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.
Inherited from FileSystemEntity.
Implementation
dart
FileStat statSync() => FileStat.statSync(path);toString() inherited
String toString()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
dart
external String toString();watch() inherited
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 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
dart
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()
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.
Implementation
dart
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
dart
void writeAsBytesSync(
List<int> bytes, {
FileMode mode = FileMode.write,
bool flush = false,
});writeAsString()
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.
Implementation
dart
Future<File> writeAsString(
String contents, {
FileMode mode = FileMode.write,
Encoding encoding = utf8,
bool flush = false,
});writeAsStringSync()
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.
Implementation
dart
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
dart
external bool operator ==(Object other);