简单了解 Dart File 类的用法

简介: 这是我参与8月更文挑战的第 5 天,活动详情查看:8月更文挑战。为应掘金的八月更文挑战,你知道的越多,意味着不知道的越多> 本文主要简单了解 Dart File 类的用法。

Dart File 类

File 表示文件系统中某个文件的引用。

File 实例是个对象,它持有 path 并对其进行操作。可以使用 parent getter 获取父目录,parent 属性继承自 FileSystemEntity

使用 pathname 创建新的 File 对象来访问文件系统上的文件。

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

File 类包含操作文件及其内容的方法。使用这些方法,可以打开和关闭文件,读写文件,创建和删除文件,以及检查文件是否存在。

读写文件时,可以使用 stream (通过 openRead),随机访问操作 (通过 open),或者类似 readAsString 这样的便捷方法。

File 类中的方法大部分都有同步和异步两种形式,比如 readAsStringreadAsStringSync。除非有特别的理由,通常应当使用异步方法以避免阻塞程序。

如果构造 File 对象的 path 是一个符号链接,而非文件,则 File 类的方法会操作链接指向的最终目标文件。不过,deletedeleteSync 方法除外,这两个方法是对符号链接进行操作。

读文件

下面示例代码使用异步的 readAsString 方法读取文件,它将整个文件内容视为一个字符串:

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

更灵活更有用的方法是使用 Stream 方式读文件。调用 openRead 方法打开文件,该方法返回 stream,这个 stream 以字节块的方式返回文件数据。可以监听 stream 来获取数据并进行必要的处理。可以继续使用不同的 transformer 操作数据来得到想要的数据格式。

可以使用 stream 方式来读取大文件,并提供 transformer 来操作数据。

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

写文件

使用 writeAsString 方法写文件。

import 'dart:io';
void main() {
  final filename = 'file.txt';
  new File(filename).writeAsString('some content')
    .then((File file) {
      // Do something with the file.
    });
}

也可以使用 Stream 来写入文件。调用 openWrite 方法打开文件,返回结果是 IOSink,可以向 IOSink 写入数据。记得操作完成后调用 IOSink.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();
}

使用 Future

为避免意外阻塞程序,File 类的一些方法使用 Future 作为返回值。比如,length 方法用于获取文件长度,返回的是 Future。调用 then 方法注册回调函数,获取到文件长度后会回调这个函数。

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

除了 length() 外,其他几个方法也返回 Future,包括:existslastModifiedstat 等等。

其他资源

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



相关文章
|
9月前
|
Dart 数据安全/隐私保护
Dart笔记:Dart 语言中的存取器及其用法解析
Dart笔记:Dart 语言中的存取器及其用法解析
108 0
|
5月前
|
Java
File类的基本使用【 File类+IO流知识回顾①】
这篇文章回顾了Java中File类的基本使用,包括创建File对象、获取文件数据信息、判断文件存在与否、创建和删除文件目录,以及遍历文件目录的方法。
File类的基本使用【 File类+IO流知识回顾①】
|
7月前
|
JSON Dart 安全
Flutter Dart Macro 宏简化 JSON 序列化
今天我们将会体验 dart 语言新特性 macro 宏,来实现对 json 的序列化,用到的包是官方实验室写的 json 包。 本文将会一步步的带你实现这个功能,那我们开始吧。
109 2
Flutter Dart Macro 宏简化 JSON 序列化
|
6月前
|
Dragonfly Dart NoSQL
Dart ffi 使用问题之在Dart中调用String的toNativeUtf8方法时有什么是需要注意的
Dart ffi 使用问题之在Dart中调用String的toNativeUtf8方法时有什么是需要注意的
|
8月前
|
C++
C++ 实现一个不能被copy的类
C++ 实现一个不能被copy的类
|
9月前
|
Java API Windows
File 类及其方法
File 类及其方法
79 1
|
存储 Android开发
Java_File类的基本用法
Java_File类的基本用法
79 0
|
Dart 开发者
【Flutter】Dart 面向对象 ( get 方法 | set 方法 | 静态方法
【Flutter】Dart 面向对象 ( get 方法 | set 方法 | 静态方法
975 0
|
Dart
Dart之 方法定义
Dart之 方法定义
129 0
Dart之 方法定义
|
Dart
Dart 之继承
Dart 之继承
91 0
Dart 之继承

热门文章

最新文章