This is the fifth day of my participation in the August More text Challenge. For details, see: August More Text Challenge. In response to the nuggets’ August challenge,

The more you know, the more you don’t know.

The Dart File class

File indicates a reference to a File in the File system.

The File instance is an object that holds the path and operates on it. You can use the parent Getter to get the parent directory. The parent attribute is inherited from FileSystemEntity.

Use pathname to create a new File object to access files on the File system.

var myFile = new File('file.txt');
Copy the code

The File class contains methods to manipulate files and their contents. Using these methods, you can open and close files, read and write files, create and delete files, and check whether files exist.

To read and write a file, you can use a stream (via openRead), a random access operation (via open), or a convenient method like readAsString.

Most of the methods in the File class come in both synchronous and asynchronous forms, such as readAsString and readAsStringSync. Unless there is a specific reason, you should usually use an asynchronous approach to avoid blocking your program.

If the path to which the File object is constructed is a symbolic link, rather than a File, then the methods of the File class operate on the final target File to which the link points. The exceptions are the delete and deleteSync methods, which operate on symbolic links.

Read the file

The following example code reads a file using the asynchronous readAsString method, which treats the entire contents of the file as a string:

import 'dart:async';
import 'dart:io';
​
void main() {
  new File('file.txt').readAsString().then((String contents) {
    print(contents);
  });
}
Copy the code

A more flexible and useful approach is to read files using Stream. The file is opened by calling the openRead method, which returns a stream that returns the file data in chunks of bytes. You can listen to the stream to get the data and do the necessary processing. You can continue to manipulate the data using different Transformer to get the data format you want.

You can use stream to read large files and provide Transformer to manipulate the data.

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()); });
}
Copy the code

Write files

Write the file using 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.
    });
}
Copy the code

You can also use Stream to write to a file. Call the openWrite method to open the file. The result is IOSink. You can write data to IOSink. Remember to call iosink.close to close sink.

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();
}
Copy the code

The use of the Future

To avoid accidentally blocking the program, some methods of the File class use Future as the return value. For example, the length method is used to get the length of the file and returns the Future. The then method is called to register the callback function, which is called back when the length of the file is obtained.

import 'dart:io';
​
main() {
  final file = new File('file.txt');
​
  file.length().then((len) {
    print(len);
  });
}
Copy the code

In addition to length(), several other methods return Future, including EXISTS, lastModified, stat, and so on.

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.
  • II/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.