Introduction to the

File manipulation is a very common operation in IO. How easy is it to manipulate files in dart? Dart actually provides two ways to read a file, either all at once or as a stream.

The disadvantage of a one-time read is that the contents of the file need to be loaded into memory at one time. If the file is large, it will be awkward. So you need a way to stream the file. Take a look at how these two files are read in DART.

File

Dart actually has a File class in many places, and the File class we’re going to cover here is in the DART: IO package.

Read the entire file

File represents a File as a whole. It has three constructors:

factory File(String path) 

factory File.fromUri(Uri uri)

factory File.fromRawPath(Uint8List rawPath)
Copy the code

The most common of these is the first constructor.

We can construct a file like this:

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

Once you have the File, you can call the various read methods in File.

File reading itself has two forms, one is text, one is binary.

If it is a text File, File provides a readAsString method that reads the entire File as a string.

  Future<String> readAsString({Encoding encoding: utf8});
Copy the code

We can use it like this:

 var stringContents = await file.readAsString();
Copy the code

Alternatively, we can read the file line by line:

Future<List<String>> readAsLines({Encoding encoding: utf8});
Copy the code

The result is a List representing the contents of each line of the file.

 var lines = await file.readAsLines();
Copy the code

While the above two methods are asynchronous, File also provides two synchronous methods:

String readAsStringSync({Encoding encoding: utf8});

List<String> readAsLinesSync({Encoding encoding: utf8});
Copy the code

If the file is binary, you can use readAsBytes or the synchronous method readAsBytesSync:

Future<Uint8List> readAsBytes();

Uint8List readAsBytesSync();
Copy the code

Dart has a special type for binary called Uint8List, which actually represents a List of ints.

Again, let’s see how to read in binary form:

var file = File('file.txt');
var contents = await file.readAsBytes();
Copy the code

Read the file as a stream

All of the methods mentioned above are to read the entire file at once. The disadvantage is that if the file is too large, it may cause memory space stress.

So File gives us another way to read files, to read files as streams.

The corresponding definition method is as follows:

  Stream<List<int>> openRead([int? start, int? end]);
Copy the code

Let’s look at a basic use:

import 'dart:io'; import 'dart:convert'; Future<void> main() async { var file = File('file.txt'); Stream<List<int>> inputStream = file.openRead(); var lines = utf8.decoder .bind(inputStream) .transform(const LineSplitter()); try { await for (final line in lines) { print('Got ${line.length} characters from stream'); } print('file is now closed'); } catch (e) { print(e); }}Copy the code

Random access

In general, files are accessed sequentially, but sometimes we need to skip some previous data and jump directly to the destination address, so files need to be accessed randomly.

Dart provides both open and openSync methods for random file reads and writes:

  Future<RandomAccessFile> open({FileMode mode: FileMode.read});
  RandomAccessFile openSync({FileMode mode: FileMode.read});
Copy the code

RandomAccessFile provides random reads and writes to files. Very useful.

File writing

Like file reads, writes can be written once or a write handle can be obtained and then written again.

There are four ways to write once, one for string and one for binary:

 Future<File> writeAsBytes(List<int> bytes,
      {FileMode mode: FileMode.write, bool flush: false});

void writeAsBytesSync(List<int> bytes,
      {FileMode mode: FileMode.write, bool flush: false});

Future<File> writeAsString(String contents,
      {FileMode mode: FileMode.write,
      Encoding encoding: utf8,
      bool flush: false});

void writeAsStringSync(String contents,
      {FileMode mode: FileMode.write,
      Encoding encoding: utf8,
      bool flush: false});
Copy the code

In the form of a handle, the openWrite method can be called to return an IOSink object from which to write:

IOSink openWrite({FileMode mode: FileMode.write, Encoding encoding: utf8});
Copy the code
var logFile = File('log.txt');
var sink = logFile.openWrite();
sink.write('FILE ACCESSED ${DateTime.now()}\n');
await sink.flush();
await sink.close();
Copy the code

By default, writing overwrites the entire file, but you can change the write mode by:

var sink = logFile.openWrite(mode: FileMode.append);
Copy the code

Handle exceptions

While all exceptions in DART are runtime exceptions, to handle exceptions in file reads and writes manually, as in Java, you can use try,catch:

Future<void> main() async { var config = File('config.txt'); try { var contents = await config.readAsString(); print(contents); } catch (e) { print(e); }}Copy the code

conclusion

So that’s file operations in DART.

This article is available at www.flydean.com

The most popular interpretation, the most profound dry goods, the most concise tutorial, many tips you didn’t know waiting for you to discover!

Welcome to pay attention to my public number: “procedures those things”, understand technology, more understand you!