Skip to content

FileSystemEntity abstract

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:

dart
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:

dart
var isThere = await entity.exists();
print(isThere ? 'exists' : 'nonexistent');

Other resources

Implementers

Constructors

FileSystemEntity()

FileSystemEntity()

Properties

absolute no setter

FileSystemEntity get absolute

A 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.

Implementation
dart
FileSystemEntity get absolute;

hashCode no setter inherited

int get hashCode

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
dart
external int get hashCode;

isAbsolute no setter

bool get isAbsolute

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.

Implementation
dart
bool get isAbsolute => _isAbsolute(path);

parent no setter

Directory get parent

The parent directory of this entity.

Implementation
dart
Directory get parent => new Directory(parentOf(path));

path no setter

String get path
Implementation
dart
String get path;

runtimeType no setter inherited

Type get runtimeType

A representation of the runtime type of the object.

Inherited from Object.

Implementation
dart
external Type get runtimeType;

uri no setter

Uri get uri

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.

Implementation
dart
Uri get uri => new Uri.file(path);

Methods

delete()

Future<FileSystemEntity> delete({bool recursive = false})

Deletes this FileSystemEntity.

The exact details vary according to the FileSystemEntity:

Implementation
dart
Future<FileSystemEntity> delete({bool recursive = false}) =>
    _delete(recursive: recursive);

deleteSync()

void deleteSync({bool recursive = false})

Synchronously deletes this FileSystemEntity.

The exact details vary according to the FileSystemEntity:

Implementation
dart
void deleteSync({bool recursive = false}) =>
    _deleteSync(recursive: recursive);

exists()

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.

Implementation
dart
Future<bool> exists();

existsSync()

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.

Implementation
dart
bool existsSync();

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 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:

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);

rename()

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.

Implementation
dart
Future<FileSystemEntity> rename(String newPath);

renameSync()

FileSystemEntity renameSync(String newPath)

Synchronously renames this file system entity.

Returns a FileSystemEntity instance for the renamed entity.

Implementation
dart
FileSystemEntity renameSync(String newPath);
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:

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.

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()

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.

Implementation
dart
String resolveSymbolicLinksSync() {
  var result = _resolveSymbolicLinks(_Namespace._namespace, _rawPath);
  _throwIfError(result, "Cannot resolve symbolic links", path);
  return result;
}

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.

Implementation
dart
Future<FileStat> stat() => FileStat.stat(path);

statSync()

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.

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()

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: Uses ReadDirectoryChangesW. The implementation only supports watching directories. Recursive watching is supported.

  • Linux: Uses inotify. 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 cancel on the StreamSubscription.
  • The FileSystemEntity being watched is deleted.
  • System Watcher exits unexpectedly. e.g. On Windows this happens when buffer that receive events from ReadDirectoryChangesW overflows.

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.

Implementation
dart
Stream<FileSystemEvent> watch({
  int events = FileSystemEvent.all,
  bool recursive = false,
}) {
  &#47;&#47; 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);
}

Operators

operator ==() inherited

bool operator ==(Object other)

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 == o must be true.

  • Symmetric: For all objects o1 and o2, o1 == o2 and o2 == o1 must either both be true, or both be false.

  • Transitive: For all objects o1, o2, and o3, if o1 == o2 and o2 == o3 are true, then o1 == o3 must 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);

Static Properties

isWatchSupported no setter

bool get isWatchSupported

Test if watch is supported on the current system.

OS X 10.6 and below is not supported.

Implementation
dart
static bool get isWatchSupported {
  final IOOverrides? overrides = IOOverrides.current;
  if (overrides == null) {
    return _FileSystemWatcher.isSupported;
  }
  return overrides.fsWatchIsSupported();
}

Static Methods

identical()

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.

Implementation
dart
static Future<bool> identical(String path1, String path2) {
  IOOverrides? overrides = IOOverrides.current;
  if (overrides == null) {
    return _identical(path1, path2);
  }
  return overrides.fseIdentical(path1, path2);
}

identicalSync()

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.

Implementation
dart
static bool identicalSync(String path1, String path2) {
  IOOverrides? overrides = IOOverrides.current;
  if (overrides == null) {
    return _identicalSync(path1, path2);
  }
  return overrides.fseIdenticalSync(path1, path2);
}

isDirectory()

Future<bool> isDirectory(String path)

Whether path refers to a directory.

Checks whether type(path) returns FileSystemEntityType.directory.

Implementation
dart
static Future<bool> isDirectory(String path) => _getType(
  _toUtf8Array(path),
  true,
).then((type) => (type == FileSystemEntityType.directory));

isDirectorySync()

bool isDirectorySync(String path)

Synchronously checks whether path refers to a directory.

Checks whether typeSync(path) returns FileSystemEntityType.directory.

Implementation
dart
static bool isDirectorySync(String path) =>
    (_getTypeSync(_toUtf8Array(path), true) ==
    FileSystemEntityType.directory);

isFile()

Future<bool> isFile(String path)

Whether path refers to a file.

Checks whether type(path) returns FileSystemEntityType.file.

Implementation
dart
static Future<bool> isFile(String path) => _getType(
  _toUtf8Array(path),
  true,
).then((type) => (type == FileSystemEntityType.file));

isFileSync()

bool isFileSync(String path)

Synchronously checks whether path refers to a file.

Checks whether typeSync(path) returns FileSystemEntityType.file.

Implementation
dart
static bool isFileSync(String path) =>
    (_getTypeSync(_toUtf8Array(path), true) == FileSystemEntityType.file);
Future<bool> isLink(String path)

Whether path refers to a link.

Checks whether type(path, followLinks: false) returns FileSystemEntityType.link.

Implementation
dart
static Future<bool> isLink(String path) => _isLinkRaw(_toUtf8Array(path));

isLinkSync()

bool isLinkSync(String path)

Synchronously checks whether path refers to a link.

Checks whether typeSync(path, followLinks: false) returns FileSystemEntityType.link.

Implementation
dart
static bool isLinkSync(String path) => _isLinkRawSync(_toUtf8Array(path));

parentOf()

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.

Implementation
dart
static String parentOf(String path) {
  int rootEnd = -1;
  if (Platform.isWindows) {
    if (path.startsWith(_absoluteWindowsPathPattern)) {
      &#47;&#47; Root ends at first &#47; or \ after the first two characters.
      rootEnd = path.indexOf(new RegExp(r'[&#47;\\]'), 2);
      if (rootEnd == -1) return path;
    } else if (path.startsWith('\\') || path.startsWith('&#47;')) {
      rootEnd = 0;
    }
  } else if (path.startsWith('&#47;')) {
    rootEnd = 0;
  }
  &#47;&#47; Ignore trailing slashes.
  &#47;&#47; All non-trivial cases have separators between two non-separators.
  int pos = path.lastIndexOf(_parentRegExp);
  if (pos > rootEnd) {
    return path.substring(0, pos + 1);
  } else if (rootEnd > -1) {
    return path.substring(0, rootEnd + 1);
  } else {
    return '.';
  }
}

type()

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.

Implementation
dart
static Future<FileSystemEntityType> type(
  String path, {
  bool followLinks = true,
}) {
  return _getType(_toUtf8Array(path), followLinks);
}

typeSync()

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.

Implementation
dart
static FileSystemEntityType typeSync(String path, {bool followLinks = true}) {
  return _getTypeSync(_toUtf8Array(path), followLinks);
}