File class

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 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 'package:node_io/node_io.dart';

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. 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.

import 'dart:convert';
import 'dart:async';

import 'package:node_io/node_io.dart';

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

  inputStream
    .transform(utf8.decoder)       // Decode bytes to UTF-8.
    .transform(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 'package:node_io/node_io.dart';

void main() {
  final filename = 'file.txt';
  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 io.IOSink to which you can write data. Be sure to close the sink with the io.IOSink.close method.

import 'package:node_io/node_io.dart';

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();
}
Implemented types

Constructors

File(String path)

Properties

absolute File
A FileSystemEntity whose path is the absolute path of path.
no setteroverride
basename String
Gets the part of this entity's path after the last separator.
no setterinherited
dirname String
Gets the part of this entity's path before the last separator.
no setterinherited
fileSystem → FileSystem
Returns the file system responsible for this entity.
no setterinherited
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
final
runtimeType Type
A representation of the runtime type of the object.
no setterinherited
uri Uri
A Uri representing the file system entity's location.
no setterinherited

Methods

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

Operators

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