File class Null safety

A reference to a file on the file system.

A File instance is an object that holds a path on which operations can be performed. You can get the parent directory of the file using the getter 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 = new 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() {
  new 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. Listen to the stream for data and process as needed. You can use various transformers in succession to manipulate the data 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';

main() {
  final file = new File('file.txt');
  Stream<List<int>> inputStream = file.openRead();

  inputStream
    .transform(utf8.decoder)       // Decode bytes to UTF-8.
    .transform(new LineSplitter()) // Convert stream to individual lines.
    .listen((String line) {        // Process results.
        print('$line: ${line.length} bytes');
      },
      onDone: () { print('File is now closed.'); },
      onError: (e) { print(e.toString()); });
}

Write to a file

To write a string to a file, use the writeAsString method:

import 'dart:io';

void main() {
  final filename = 'file.txt';
  new File(filename).writeAsString('some content')
    .then((File file) {
      // 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 = new File('file.txt');
  var sink = file.openWrite();
  sink.write('FILE ACCESSED ${new DateTime.now()}\n');

  // Close the IOSink to free system resources.
  sink.close();
}

The use of Futures

To avoid unintentional blocking of the program, several methods use a Future to return a value. For example, the length method, which gets the length of a file, returns a Future. Use then to register a callback function, which is called when the value is ready.

import 'dart:io';

main() {
  final file = new File('file.txt');

  file.length().then((len) {
    print(len);
  });
}

In addition to length, the exists, lastModified, stat, and other methods, return Futures.

Other resources

  • Dart by Example provides additional task-oriented code samples that show how to use various API from the Directory class and the related File class.

  • I/O for Command-Line Apps a section from A Tour of the Dart Libraries covers files and directories.

  • Write Command-Line Apps, a tutorial about writing command-line apps, includes information about files and directories.

Implemented types

Constructors

File(String path)
Creates a File object. [...]
factory
File.fromRawPath(Uint8List rawPath)
Creates a File object from a raw path, that is, a sequence of bytes as represented by the OS.
factory
File.fromUri(Uri uri)
Create a File object from a URI. [...]
factory

Properties

absolute File
Returns a File instance whose path is the absolute path to this. [...]
read-only, override
hashCode int
The hash code for this object. [...]
read-only, inherited
isAbsolute bool
Returns a bool indicating whether this object's path is absolute. [...]
read-only, inherited
parent Directory
The directory containing this.
read-only, inherited
path String
Get the path of the file.
read-only, override
runtimeType Type
A representation of the runtime type of the object.
read-only, inherited
uri Uri
Returns a Uri representing the file system entity's location. [...]
read-only, inherited

Methods

copy(String newPath) Future<File>
Copy this file. Returns a Future<File> that completes with a File instance for the copied file. [...]
copySync(String newPath) File
Synchronously copy this file. Returns a File instance for the copied file. [...]
create({bool recursive: false}) Future<File>
Create the file. Returns a Future<File> that completes with the file when it has been created. [...]
createSync({bool recursive: false}) → void
Synchronously create the file. Existing files are left untouched by createSync. Calling createSync on an existing file might fail if there are restrictive permissions on the file. [...]
delete({bool recursive: false}) Future<FileSystemEntity>
Deletes this FileSystemEntity. [...]
inherited
deleteSync({bool recursive: false}) → void
Synchronously deletes this FileSystemEntity. [...]
inherited
exists() Future<bool>
Checks whether the file system entity with this path exists. Returns a Future<bool> that completes with the result. [...]
inherited
existsSync() bool
Synchronously checks whether the file system entity with this path exists. [...]
inherited
lastAccessed() Future<DateTime>
Get the last-accessed time of the file. [...]
lastAccessedSync() DateTime
Get 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>
Get the length of the file. Returns a Future<int> that completes with the length in bytes.
lengthSync() int
Synchronously get the length of the file. [...]
noSuchMethod(Invocation invocation) → dynamic
Invoked when a non-existent method or property is accessed. [...]
inherited
open({FileMode mode: FileMode.read}) Future<RandomAccessFile>
Open 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. [...]
openRead([int? start, int? end]) Stream<List<int>>
Create a new independent Stream for the contents of this file. [...]
openSync({FileMode mode: FileMode.read}) RandomAccessFile
Synchronously open 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. [...]
openWrite({FileMode mode: FileMode.write, Encoding encoding: utf8}) IOSink
Creates a new independent IOSink for the file. The IOSink must be closed when no longer used, to free system resources. [...]
readAsBytes() Future<Uint8List>
Read 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.
readAsBytesSync() Uint8List
Synchronously read the entire file contents as a list of bytes. [...]
readAsLines({Encoding encoding: utf8}) Future<List<String>>
Read the entire file contents as lines of text using the given Encoding. [...]
readAsLinesSync({Encoding encoding: utf8}) List<String>
Synchronously read the entire file contents as lines of text using the given Encoding. [...]
readAsString({Encoding encoding: utf8}) Future<String>
Read the entire file contents as a string using the given Encoding. [...]
readAsStringSync({Encoding encoding: utf8}) String
Synchronously read the entire file contents as a string using the given Encoding. [...]
rename(String newPath) Future<File>
Renames this file. Returns a Future<File> that completes with a File instance for the renamed file. [...]
override
renameSync(String newPath) File
Synchronously renames this file. Returns a File instance for the renamed file. [...]
override
Resolves the path of a file system object relative to the current working directory. [...]
inherited
resolveSymbolicLinksSync() String
Resolves the path of a file system object relative to the current working directory. [...]
inherited
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>
Calls the operating system's stat() function on the path of this FileSystemEntity. [...]
inherited
statSync() FileStat
Synchronously calls the operating system's stat() function on the path of this FileSystemEntity. [...]
inherited
toString() String
Returns a string representation of this object.
inherited
watch({int events: FileSystemEvent.all, bool recursive: false}) Stream<FileSystemEvent>
Start watching the FileSystemEntity for changes. [...]
inherited
writeAsBytes(List<int> bytes, {FileMode mode: FileMode.write, bool flush: false}) Future<File>
Write a list of bytes to a file. [...]
writeAsBytesSync(List<int> bytes, {FileMode mode: FileMode.write, bool flush: false}) → void
Synchronously write a list of bytes to a file. [...]
writeAsString(String contents, {FileMode mode: FileMode.write, Encoding encoding: utf8, bool flush: false}) Future<File>
Write a string to a file. [...]
writeAsStringSync(String contents, {FileMode mode: FileMode.write, Encoding encoding: utf8, bool flush: false}) → void
Synchronously write a string to a file. [...]

Operators

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