一統天下 flutter - 存儲: File, Directory - 文件操作, 目錄操作
示例如下:
lib\storage\file.dart
/*
* File - 文件操作
* Directory - 目錄操作
* File 和 Directory 都繼承自 FileSystemEntity
*/
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:flutter/services.dart' show Uint8List, rootBundle;
import '../helper.dart';
class FileDemo extends StatefulWidget {
const FileDemo({Key? key}) : super(key: key);
@override
_FileDemoState createState() => _FileDemoState();
}
class _FileDemoState extends State<FileDemo> {
String _content = "";
Uint8List _imageData = Uint8List.fromList([]);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text("title"),),
backgroundColor: Colors.orange,
body: Center(
child: Column(
children: [
ElevatedButton(
onPressed: () async {
var dir = await getApplicationDocumentsDirectory();
/// 根據文件路徑實例化 File 對象
final file = File('${dir.path}/data.txt');
/// 在指定的文件寫入指定內容的文本,文件不存在則創建,文件存在則重寫
await file.writeAsString("hello ${currentTimestamp()}", encoding: utf8);
},
child: const Text('寫文本文件',),
),
ElevatedButton(
onPressed: () async {
var dir = await getApplicationDocumentsDirectory();
/// 根據文件路徑實例化 File 對象
final file = File('${dir.path}/data.txt');
/// 從指定的文件讀取文本內容
final content = await file.readAsString(encoding: utf8);
setState(() {
_content = content;
});
},
child: const Text('讀文本文件',),
),
ElevatedButton(
onPressed: () async {
var dir = await getApplicationDocumentsDirectory();
/// 根據目錄路徑實例化 Directory 對象
final myDir = Directory('${dir.path}/a/b/c');
/// 判斷目錄是否存在
var myDirExists = await myDir.exists();
if (!myDirExists) {
/// 創建目錄
/// recursive 爲 true 則會遞歸創建多級目錄
await myDir.create(recursive: true);
}
},
child: const Text('創建目錄',),
),
ElevatedButton(
onPressed: () async {
var dir = await getApplicationDocumentsDirectory();
for (int i = 1; i < 10; i++) {
/// 根據文件路徑實例化 File 對象
final file = File('${dir.path}/x/y/z/data$i.txt');
/// 判斷文件是否存在
var fileExists = await file.exists();
/// 創建文件
/// recursive 爲 true 則會遞歸創建多級目錄
/// exclusive 爲 true 則當文件存在時,會拋出異常
/// exclusive 爲 false 則當文件存在時,不會做任何處理
file.create(recursive: true, exclusive: false);
}
},
child: const Text('創建文件',),
),
ElevatedButton(
onPressed: () async {
var dir = await getApplicationDocumentsDirectory();
/// 遍歷指定的目錄
/// recursive 爲 true 則會遞歸遍歷多級目錄
var stream = dir.list(recursive: true);
await for (final FileSystemEntity fse in stream) {
if (fse is File) { /// 當前遍歷出的結果是 File 對象
log('file: ${fse.path}'); /// File 的路徑
} else if (fse is Directory) { /// 當前遍歷出的結果是 Directory 對象
log('dir: ${fse.path}'); /// Directory 的路徑
}
}
},
child: const Text('遍歷目錄和文件',),
),
ElevatedButton(
onPressed: () async {
var dir = await getApplicationDocumentsDirectory();
final file = File('${dir.path}/son.jpg');
var bytes = await rootBundle.load("assets/son.jpg");
var imageData = bytes.buffer.asUint8List(bytes.offsetInBytes, bytes.lengthInBytes);
/// 寫入指定的二進制數據
file.writeAsBytes(imageData);
},
child: const Text('寫二進制數據',),
),
ElevatedButton(
onPressed: () async {
var dir = await getApplicationDocumentsDirectory();
final file = File('${dir.path}/son.jpg');
if (await file.exists()) {
/// 從指定的文件讀取二進制內容
_imageData = await file.readAsBytes();
setState(() {});
}
},
child: const Text('讀二進制數據',),
),
ElevatedButton(
onPressed: () async {
var dir = await getApplicationDocumentsDirectory();
final file = File('${dir.path}/son.jpg');
if (await file.exists()) {
/// 刪除指定的文件
await file.delete();
}
/// 刪除指定的目錄
/// recursive 爲 true 則會遞歸刪除多級目錄以及目錄中的文件
await dir.delete(recursive: true);
},
child: const Text('刪除目錄和文件',),
),
ElevatedButton(
onPressed: () async {
var dir = await getApplicationDocumentsDirectory();
final file = File('${dir.path}/son.jpg');
/// 重命名
/// await file.rename("new name");
/// 複製文件
/// await file.copy("new path");
/// 獲取當前文件的目錄
/// var parentDir = file.parent;
/// 獲取文件的大小
/// var length = await file.length();
/// 獲取文件的最近訪問時間
/// var lastAccessed = await file.lastAccessed();
/// 獲取文件的最近修改時間
/// var lastModified = await file.lastModified();
/// 設置文件的最近訪問時間
/// await file.setLastAccessed(DateTime.now());
/// 設置文件的最近修改時間
/// await file.setLastModified(DateTime.now());
/// 獲取當前文件的狀態
var stat = await file.stat();
setState(() {
/// size - 文件大小
/// accessed - 最近訪問時間
/// modified - 最近修改時間
/// type - 當前 FileSystemEntity 的類型
/// FileSystemEntityType.file - 文件
/// FileSystemEntityType.directory - 目錄
/// FileSystemEntityType.notFound - 不存在
_content = 'size:${stat.size}, accessed:${stat.accessed}, modified:${stat.modified}, type:${stat.type}';
});
},
child: const Text('其他操作',),
),
MyTextSmall(_content),
Builder(
builder: (BuildContext context) {
if (_imageData.isEmpty) {
return Container();
} else {
return Image.memory(_imageData,
width: 50,
height: 50,
);
}
}
),
],
),
),
);
}
}