File class Null safety
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 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() {
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
-
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
Properties
- absolute → File
-
A File with the absolute path of path. [...]
read-only, override
- hashCode → int
-
The hash code for this object. [...]
read-only, inherited
- isAbsolute → bool
-
Whether this object's path is absolute. [...]
read-only, inherited
- parent → Directory
-
The parent directory of this entity.
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
-
A Uri representing the file system entity's location. [...]
read-only, inherited
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> -
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. [...]
inherited
-
existsSync(
) → bool -
Synchronously checks whether the file system entity with this path
exists. [...]
inherited
-
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 -
Invoked when a non-existent method or property is accessed. [...]
inherited
-
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> -
Renames this file. [...]
override
-
renameSync(
String newPath) → File -
Synchronously renames this file. [...]
override
-
resolveSymbolicLinks(
) → Future< String> -
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 path. [...]inherited -
statSync(
) → FileStat -
Synchronously calls the operating system's
stat()
function on path. [...]inherited -
toString(
) → String -
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> - 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 -
The equality operator. [...]
inherited