读取和写入文件
如何从磁盘读取文件以及向磁盘写入文件。
在某些情况下,您需要读写磁盘文件。例如,您可能需要跨应用启动持久化保存数据,或者下载网络数据并将其保存以供稍后离线使用。
要在移动设备或桌面端应用中将文件保存到磁盘,请结合使用 path_provider 插件和 dart:io 库。
本示例将采取以下步骤
- 查找正确的本地路径。
- 创建文件位置的引用。
- 将数据写入文件。
- 从文件读取数据。
欲了解更多信息,请观看此“每周插件 (Package of the Week)”视频,了解 path_provider 插件
1. 查找正确的本地路径
#本示例显示一个计数器。当计数器更改时,将数据写入磁盘,以便在应用加载时能够再次读取它。您应该将这些数据存储在哪里?
path_provider 插件提供了一种平台无关的方式来访问设备文件系统中常用的位置。该插件目前支持访问两个文件系统位置:
- 临时目录 (Temporary directory)
-
系统可以随时清除的临时目录(缓存)。在 iOS 上,这对应于
NSCachesDirectory。在 Android 上,这是getCacheDir()返回的值。 - 文档目录 (Documents directory)
-
供应用存储只有自身可以访问的文件的目录。系统仅在删除应用时才会清除该目录。在 iOS 上,这对应于
NSDocumentDirectory。在 Android 上,这是AppData目录。
本示例将信息存储在文档目录中。您可以按如下方式查找文档目录的路径:
import 'package:path_provider/path_provider.dart';
// ···
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
2. 创建文件位置的引用
#一旦知道将文件存储在哪里,请创建该文件完整位置的引用。您可以使用 dart:io 库中的 File 类来实现这一点。
Future<File> get _localFile async {
final path = await _localPath;
return File('$path/counter.txt');
}
3. 将数据写入文件
#现在您已经拥有了可供操作的 File,可以使用它来读取和写入数据。首先,将一些数据写入文件。计数器是一个整数,但使用 '$counter' 语法将其作为字符串写入文件。
Future<File> writeCounter(int counter) async {
final file = await _localFile;
// Write the file
return file.writeAsString('$counter');
}
4. 从文件读取数据
#现在磁盘上已经有一些数据了,您可以读取它。再次使用 File 类。
Future<int> readCounter() async {
try {
final file = await _localFile;
// Read the file
final contents = await file.readAsString();
return int.parse(contents);
} catch (e) {
// If encountering an error, return 0
return 0;
}
}
完整示例
#import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
void main() {
runApp(
MaterialApp(
title: 'Reading and Writing Files',
home: FlutterDemo(storage: CounterStorage()),
),
);
}
class CounterStorage {
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<File> get _localFile async {
final path = await _localPath;
return File('$path/counter.txt');
}
Future<int> readCounter() async {
try {
final file = await _localFile;
// Read the file
final contents = await file.readAsString();
return int.parse(contents);
} catch (e) {
// If encountering an error, return 0
return 0;
}
}
Future<File> writeCounter(int counter) async {
final file = await _localFile;
// Write the file
return file.writeAsString('$counter');
}
}
class FlutterDemo extends StatefulWidget {
const FlutterDemo({super.key, required this.storage});
final CounterStorage storage;
@override
State<FlutterDemo> createState() => _FlutterDemoState();
}
class _FlutterDemoState extends State<FlutterDemo> {
int _counter = 0;
@override
void initState() {
super.initState();
widget.storage.readCounter().then((value) {
setState(() {
_counter = value;
});
});
}
Future<File> _incrementCounter() {
setState(() {
_counter++;
});
// Write the variable as a string to the file.
return widget.storage.writeCounter(_counter);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Reading and Writing Files')),
body: Center(
child: Text('Button tapped $_counter time${_counter == 1 ? '' : 's'}.'),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}