简单了解 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.



相关文章
|
29天前
|
Java
File类的基本使用【 File类+IO流知识回顾①】
这篇文章回顾了Java中File类的基本使用,包括创建File对象、获取文件数据信息、判断文件存在与否、创建和删除文件目录,以及遍历文件目录的方法。
File类的基本使用【 File类+IO流知识回顾①】
|
2月前
|
对象存储 Python
Python代码解读-理解-定义一个User类的基本写法
以上描述清晰地阐述了如何在Python中定义 `User`类的基本方法以及如何创建和使用该类的实例。这是面向对象编程中的核心概念,是紧密结合抽象和实现,封装数据并提供操作数据的接口。由于用简单通用的语言易于理解,这样的解释对于初学者而言应该是友好且有帮助的。
35 4
|
2月前
|
Dragonfly Dart NoSQL
Dart ffi 使用问题之在Dart中调用String的toNativeUtf8方法时有什么是需要注意的
Dart ffi 使用问题之在Dart中调用String的toNativeUtf8方法时有什么是需要注意的
|
存储 Android开发
Java_File类的基本用法
Java_File类的基本用法
61 0
|
Java Kotlin
Kotlin data数据类、copy()函数、sealed密封类
Kotlin data数据类、copy()函数、sealed密封类使用
166 0
|
JSON 开发工具 数据格式
CommonAPI使用例子-HelloWorld
CommonAPI使用例子-HelloWorld
CommonAPI使用例子-HelloWorld
|
Dart
Dart之 方法定义
Dart之 方法定义
102 0
Dart之 方法定义
|
Dart
Dart之 对象call方法
Dart之 对象call方法
201 0
Dart之 对象call方法
在ROS 中 功能包 中将类的函数定义 与 声明 分开 文件写 用main.cpp 调用 如何配置 CmakeList.txt
在ROS 中 功能包 中将类的函数定义 与 声明 分开 文件写 用main.cpp 调用 如何配置 CmakeList.txt
在ROS 中 功能包 中将类的函数定义  与 声明 分开 文件写  用main.cpp 调用  如何配置  CmakeList.txt
|
缓存 Dart 编译器
Dart 代码的组件集合Dart VM2
这是我参与8月更文挑战的第 7 天,活动详情查看:8月更文挑战。为应掘金的八月更文挑战, Dart 代码的组件集合Dart VM 2
186 1