File class

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 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() {
  var file = File('file.txt');
  var sink = file.openWrite();
  sink.write('FILE ACCESSED ${DateTime.now()}\n');

  // Close the IOSink to free system resources.
  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.

Other resources

Implemented types

Constructors

File(String path)
factory
Creates a File object. [...]
File.fromRawPath(Uint8List rawPath)
factory
Creates a File object from a raw path. [...]
File.fromUri(Uri uri)
factory
Create a File object from a URI. [...]

Properties

absoluteFile
read-only, override
A File with the absolute path of path. [...]
hashCodeint
read-only, inherited
The hash code for this object. [...]
isAbsolutebool
read-only, inherited
Whether this object's path is absolute. [...]
parentDirectory
read-only, inherited
The parent directory of this entity.
pathString
read-only, override
Get the path of the file.
runtimeTypeType
read-only, inherited
A representation of the runtime type of the object.
uriUri
read-only, inherited
A Uri representing the file system entity's location. [...]

Methods

copy(String newPath) → Future<File>
Copies this file. [...]
copySync(String newPath) → File
Synchronously copies this file. [...]
create({bool recursive = false}) → Future<File>
Creates the file. [...]
createSync({bool recursive = false}) → void
Synchronously creates the file. [...]
delete({bool recursive = false}) → Future<FileSystemEntity>
inherited
Deletes this FileSystemEntity. [...]
deleteSync({bool recursive = false}) → void
inherited
Synchronously deletes this FileSystemEntity. [...]
exists() → Future<bool>
inherited
Checks whether the file system entity with this path exists. [...]
existsSync() → bool
inherited
Synchronously checks whether the file system entity with this path exists. [...]
lastAccessed() → Future<DateTime>
The last-accessed time of the file. [...]
lastAccessedSync() → DateTime
The last-accessed time of the file. [...]
lastModified() → Future<DateTime>
Get the last-modified time of the file. [...]
lastModifiedSync() → DateTime
Get the last-modified time of the file. [...]
length() → Future<int>
The length of the file. [...]
lengthSync() → int
The length of the file provided synchronously. [...]
noSuchMethod(Invocation invocation) → dynamic
inherited
Invoked when a non-existent method or property is accessed. [...]
open({FileMode mode = FileMode.read}) → Future<RandomAccessFile>
Opens the file for random access operations. [...]
openRead([int? start, int? end]) → Stream<List<int>>
Creates a new independent Stream for the contents of this file. [...]
openSync({FileMode mode = FileMode.read}) → RandomAccessFile
Synchronously opens the file for random access operations. [...]
openWrite({FileMode mode = FileMode.write, Encoding encoding = utf8}) → IOSink
Creates a new independent IOSink for the file. [...]
readAsBytes() → Future<Uint8List>
Reads the entire file contents as a list of bytes. [...]
readAsBytesSync() → Uint8List
Synchronously reads the entire file contents as a list of bytes. [...]
readAsLines({Encoding encoding = utf8}) → Future<List<String>>
Reads the entire file contents as lines of text using the given Encoding. [...]
readAsLinesSync({Encoding encoding = utf8}) → List<String>
Synchronously reads the entire file contents as lines of text using the given Encoding. [...]
readAsString({Encoding encoding = utf8}) → Future<String>
Reads the entire file contents as a string using the given Encoding. [...]
readAsStringSync({Encoding encoding = utf8}) → String
Synchronously reads the entire file contents as a string using the given Encoding. [...]
rename(String newPath) → Future<File>
override
Renames this file. [...]
renameSync(String newPath) → File
override
Synchronously renames this file. [...]
Resolves the path of a file system object relative to the current working directory. [...]
resolveSymbolicLinksSync() → String
inherited
Resolves the path of a file system object relative to the current working directory. [...]
setLastAccessed(DateTime time) → Future
Modifies the time the file was last accessed. [...]
setLastAccessedSync(DateTime time) → void
Synchronously modifies the time the file was last accessed. [...]
setLastModified(DateTime time) → Future
Modifies the time the file was last modified. [...]
setLastModifiedSync(DateTime time) → void
Synchronously modifies the time the file was last modified. [...]
stat() → Future<FileStat>
inherited
Calls the operating system's stat() function on path. [...]
statSync() → FileStat
inherited
Synchronously calls the operating system's stat() function on path. [...]
toString() → String
inherited
A string representation of this object. [...]
watch({int events = FileSystemEvent.all, bool recursive = false}) → Stream<FileSystemEvent>
inherited
Start watching the FileSystemEntity for changes. [...]
writeAsBytes(List<int> bytes, {FileMode mode = FileMode.write, bool flush = false}) → Future<File>
Writes a list of bytes to a file. [...]
writeAsBytesSync(List<int> bytes, {FileMode mode = FileMode.write, bool flush = false}) → void
Synchronously writes a list of bytes to a file. [...]
writeAsString(String contents, {FileMode mode = FileMode.write, Encoding encoding = utf8, bool flush = false}) → Future<File>
Writes a string to a file. [...]
writeAsStringSync(String contents, {FileMode mode = FileMode.write, Encoding encoding = utf8, bool flush = false}) → void
Synchronously writes a string to a file. [...]

Operators

operator ==(Object other) → bool
inherited
The equality operator. [...]

© 2012 the Dart project authors
Licensed under the Creative Commons Attribution-ShareAlike License v4.0.
https://api.dart.dev/stable/2.13.0/dart-io/File-class.html