File class

A reference to a file on the file system.

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 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() {
  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 tranformers, 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 UTF8.
    .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 a stream to which you can write data. Be sure to close the file with the 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

Implements:

Constructors

File ( String path )
Creates a File object.
File.fromUri ( Uri uri )
Create a File object from a URI.

Instance Properties

absolute File
read-only
path String
read-only
isAbsolute bool Inherited
read-only
parent Directory Inherited
read-only
uri Uri Inherited
read-only

Instance Methods

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.
rename ( String newPath ) → Future<File>
Renames this file. Returns a Future<File> that completes with a File instance for the renamed file.
renameSync ( String newPath ) → File
Synchronously renames this file. Returns a File instance for the renamed file.
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.
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.
lastModified ( ) → Future<DateTime>
Get the last-modified time of the file. Returns a Future<DateTime> that completes with a DateTime object for the modification date.
lastModifiedSync ( ) → DateTime
Get the last-modified time of the file. Throws an exception if the file does not exist.
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.c...
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 [Ra...
openRead ( [int start, int end] ) → Stream<List<int>>
Create a new independent Stream for the contents of this file.
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<List<int>>
Read the entire file contents as a list of bytes. Returns a Future<List<int>> that completes with the list of bytes that is the contents of the file.
readAsBytesSync ( ) → List<int>
Synchronously read the entire file contents as a list of bytes.
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.
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.
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.
watch Inherited ( {int events: FileSystemEvent.ALL, bool recursive: false} ) → Stream<FileSystemEvent>
Start watching the FileSystemEntity for changes.
Resolves the path of a file system object relative to the current working directory, resolving all symbolic links on the path and resolving all .. and . path segments.
deleteSync Inherited ( {bool recursive: false} ) → void
Synchronously deletes this FileSystemEntity.
stat Inherited ( ) → Future<FileStat>
Calls the operating system's stat() function on the path of this FileSystemEntity. Identical to FileStat.stat(this.path).
resolveSymbolicLinksSync Inherited ( ) → String
Resolves the path of a file system object relative to the current working directory, resolving all symbolic links on the path and resolving all .. and . path segments.
existsSync Inherited ( ) → bool
Synchronously checks whether the file system entity with this path exists.
delete Inherited ( {bool recursive: false} ) → Future<FileSystemEntity>
Deletes this FileSystemEntity.
exists Inherited ( ) → Future<bool>
Checks whether the file system entity with this path exists. Returns a Future<bool> that completes with the result.
statSync Inherited ( ) → FileStat
Synchronously calls the operating system's stat() function on the path of this FileSystemEntity. Identical to FileStat.statSync(this.path).