[英]How to read and write a text file in Flutter
如何从文件中读取文本并将文本写入文件?
我一直在学习如何在文件中读写文本。 我发现了另一个关于reading from assets的问题,但那是不一样的。 我将根据我从文档中学到的知识在下面添加我的答案。
在pubspec.yaml
添加以下插件:
dependencies:
path_provider: ^1.6.27
将版本号更新为当前的任何版本。
并将其导入到您的代码中。
import 'package:path_provider/path_provider.dart';
您还必须导入dart:io
才能使用File
类。
import 'dart:io';
_write(String text) async {
final Directory directory = await getApplicationDocumentsDirectory();
final File file = File('${directory.path}/my_file.txt');
await file.writeAsString(text);
}
Future<String> _read() async {
String text;
try {
final Directory directory = await getApplicationDocumentsDirectory();
final File file = File('${directory.path}/my_file.txt');
text = await file.readAsString();
} catch (e) {
print("Couldn't read file");
}
return text;
}
join(directory.path, 'my_file.txt')
获取路径字符串,但您需要导入'package:path/path.dart'
。从设备中拉取文件的另一种方法是使用 adb pull 命令。 您可以通过调试代码找到文件路径,然后使用 adb pull 命令。 adb 位于 Android SDK -> platform-tools 目录。
./adb pull /storage/emulated/0/Android/data/com.innovate.storage.storage_sample/files/sample.txt ~/Downloads
@Suragch 的回答是正确的。 除了您现在要使用的path_provider
版本是:
path_provider: ^2.0.9
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.