A reference to a file on the file system.
AFile holds apath on which operations can be performed.You can get the parent directory of the file usingparent,a property inherited fromFileSystemEntity.
Create a newFile object with a pathname to access the specified file on thefile system from your program.
var myFile = File('file.txt');TheFile class contains methods for manipulating files and their contents.Using methods in this class, you can open and close files, read to and writefrom them, create and delete them, and check for their existence.
When reading or writing a file, you can use streams (withopenRead),random access operations (withopen),or convenience methods such asreadAsString,
Most methods in this class occur in synchronous and asynchronous pairs,for example,readAsString andreadAsStringSync.Unless you have a specific reason for using the synchronous versionof a method, prefer the asynchronous version to avoid blocking your program.
If path is a link
Ifpath is a symbolic link, rather than a file,then the methods ofFile operate on the ultimate target of thelink, except fordelete anddeleteSync, which operate onthe link.
Read from a file
The following code sample reads the entire contents from a file as a stringusing the asynchronousreadAsString 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 aStream.Open the file withopenRead, which returns a stream thatprovides 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 thefile 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 asWebSockets.
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 thewriteAsString 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 aStream. Open the file withopenWrite, which returns anIOSink to which you can write data.Be sure to close the sink with theIOSink.close method.
import 'dart:io';void main() async { var file = File('file.txt'); var sink = file.openWrite(); sink.write('FILE ACCESSED ${DateTime.now()}\n'); await sink.flush(); // Close the IOSink to free system resources. await sink.close();}The use of asynchronous methods
To avoid unintentional blocking of the program,several methods are asynchronous and return aFuture. For example,thelength method, which gets the length of a file, returns aFuture.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, theexists,lastModified,stat, andother methods, are asynchronous.
Special 'nul' file
On Linux and Mac '/dev/null' and on Windows '\?\NUL' refer to a special file,such that all writes to it get consumed and disappear, and all reads produce emptyoutput. Note that on Windows 'nul'(without '\?'-prefix) refers to a regular filenamed 'nul' in current directory.
Other resources
TheFiles and directoriessection of the library tour.
Write Command-Line Apps,a tutorial about writing command-line apps, includes information aboutfiles and directories.
- Implemented types
Constructors
- File(Stringpath)
- Creates aFile object.factory
- File.fromRawPath(Uint8ListrawPath)
- Creates aFile object from a raw path.factory
- File.fromUri(Uriuri)
- Create aFile object from a URI.factory
Properties
- absolute→File
- AFile with the absolute path ofpath.no setteroverride
- hashCode→int
- The hash code for this object.no setterinherited
- isAbsolute→bool
- Whether this object's path is absolute.no setterinherited
- parent→Directory
- The parent directory of this entity.no setterinherited
- path→String
- Get the path of the file.no setteroverride
- runtimeType→Type
- A representation of the runtime type of the object.no setterinherited
- uri→Uri
- AUri representing the file system entity's location.no setterinherited
Methods
- copy(
StringnewPath)→Future< File> - Copies this file.
- copySync(
StringnewPath)→File - Synchronously copies this file.
- create(
{boolrecursive =false,boolexclusive =false})→Future< File> - Creates the file.
- createSync(
{boolrecursive =false,boolexclusive =false})→ void - Synchronously creates the file.
- delete(
{boolrecursive =false})→Future< FileSystemEntity> - Deletes thisFile.override
- deleteSync(
{boolrecursive =false})→ void - Synchronously deletes thisFile.override
- 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 pathexists.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(
Invocationinvocation)→ dynamic - Invoked when a nonexistent method or property is accessed.inherited
- open(
{FileModemode =FileMode.read})→Future< RandomAccessFile> - Opens the file for random access operations.
- openRead(
[int?start,int?end])→Stream< List< int> > - Creates a new independentStream for the contents of this file.
- openSync(
{FileModemode =FileMode.read})→RandomAccessFile - Synchronously opens the file for random access operations.
- openWrite(
{FileModemode =FileMode.write,Encodingencoding =utf8})→IOSink - Creates a new independentIOSink 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(
{Encodingencoding =utf8})→Future< List< String> > - Reads the entire file contents as lines of text using the givenEncoding.
- readAsLinesSync(
{Encodingencoding =utf8})→List< String> - Synchronously reads the entire file contents as lines of textusing the givenEncoding.
- readAsString(
{Encodingencoding =utf8})→Future< String> - Reads the entire file contents as a string using the givenEncoding.
- readAsStringSync(
{Encodingencoding =utf8})→String - Synchronously reads the entire file contents as a string using thegivenEncoding.
- rename(
StringnewPath)→Future< File> - Renames this file.override
- renameSync(
StringnewPath)→File - Synchronously renames this file.override
- resolveSymbolicLinks(
)→Future< String> - Resolves the path of a file system object relative to thecurrent working directory.inherited
- resolveSymbolicLinksSync(
)→String - Resolves the path of a file system object relative to thecurrent working directory.inherited
- setLastAccessed(
DateTimetime)→Future - Modifies the time the file was last accessed.
- setLastAccessedSync(
DateTimetime)→ void - Synchronously modifies the time the file was last accessed.
- setLastModified(
DateTimetime)→Future - Modifies the time the file was last modified.
- setLastModifiedSync(
DateTimetime)→ void - Synchronously modifies the time the file was last modified.
- stat(
)→Future< FileStat> - Calls the operating system's
stat()function onpath.inherited - statSync(
)→FileStat - Synchronously calls the operating system's
stat()function onpath.inherited - toString(
)→String - A string representation of this object.inherited
- watch(
{intevents =FileSystemEvent.all,boolrecursive =false})→Stream< FileSystemEvent> - Start watching theFileSystemEntity for changes.inherited
- writeAsBytes(
List< int> bytes, {FileModemode =FileMode.write,boolflush =false})→Future<File> - Writes a list of bytes to a file.
- writeAsBytesSync(
List< int> bytes, {FileModemode =FileMode.write,boolflush =false})→ void - Synchronously writes a list of bytes to a file.
- writeAsString(
Stringcontents, {FileModemode =FileMode.write,Encodingencoding =utf8,boolflush =false})→Future< File> - Writes a string to a file.
- writeAsStringSync(
Stringcontents, {FileModemode =FileMode.write,Encodingencoding =utf8,boolflush =false})→ void - Synchronously writes a string to a file.
Operators
- operator ==(
Objectother)→bool - The equality operator.inherited