Introduction

File operation is a very common operation in IO, so for the dart language, is it easy to manipulate files? In fact, dart provides two ways to read files, one is to read all at once, and the other is to read the file as a stream.

The disadvantage of the one-time reading is that the contents of the file need to be loaded into the memory at one time. If the file is relatively large, it will be more embarrassing. Therefore, a way to read files in a stream is also needed. Let's take a look at how these two files are read in dart.

File

In fact, there are many places in dart that have the File class. The File class we are going to explain here is in the dart:io package.

Read the entire file

File represents a whole file, he has three constructors, namely:

factory File(String path) 

factory File.fromUri(Uri uri)

factory File.fromRawPath(Uint8List rawPath)

One of the most commonly used is the first constructor.

We can construct a file like this:

var file = File('file.txt');

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

There are two forms of file reading, one is text and the other is binary.

If it is a text file, File provides a readAsString method to read the entire file as a string.

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

We can use it like this:

 var stringContents = await file.readAsString();

In addition, we can also read the file line by line:

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

The result returned is a List, which represents the content of each line of the file.

 var lines = await file.readAsLines();

The above two methods are asynchronous methods, File also provides two synchronous methods:

String readAsStringSync({Encoding encoding: utf8});

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

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

Future<Uint8List> readAsBytes();

Uint8List readAsBytesSync();

In dart, there is a special type called Uint8List for binary, which actually represents a List of ints.

Still the file just now, let's see how to read it in binary form:

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

Read the file as a stream

The reading method we mentioned above is to read the entire file at once. The disadvantage is that if the file is too large, it may cause pressure on the memory space.

So File provides us with another way to read files, in the form of streams to read files.

The corresponding definition method is as follows:

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

We 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);
  }
}

Random access

Generally, files are accessed sequentially, but sometimes we need to skip some of the previous data and jump directly to the target address, which requires random access to the file.

Dart provides two methods, open and openSync, to read and write random files:

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

RandomAccessFile provides random read and write methods for files. very useful.

File writing

Writing is the same as file reading, you can write in one time or get a write handle, and then write again.

There are four methods for one-time write, corresponding to string and 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});

The handle form can call the openWrite method, return an IOSink object, and then write through this object:

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

By default, writing will cover the entire file, but you can change the writing mode in the following ways:

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

Handle exception

Although all exceptions in dart are runtime exceptions, like java, if you want to manually handle exceptions in file reading and writing, 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);
  }
}

Summarize

The above is the file operation in dart.

This article has been included in http://www.flydean.com/23-dart-file/

The most popular interpretation, the most profound dry goods, the most concise tutorial, and many tips you don't know are waiting for you to discover!

Welcome to pay attention to my official account: "programs, those things", know the technology, know you better!


flydean
890 声望437 粉丝

欢迎访问我的个人网站:www.flydean.com