讀取和寫入檔案
如何從磁碟讀取檔案以及向磁碟寫入檔案。
在某些情況下,您需要讀寫磁碟檔案。例如,您可能需要跨應用啟動持久化儲存資料,或者下載網路資料並將其儲存以供稍後離線使用。
要在移動裝置或桌面端應用中將檔案儲存到磁碟,請結合使用 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),
),
);
}
}