flutter - Flutter 创建文件并写入其内容
问题描述
我正在开发一个从服务器收集文本内容的应用程序,下一步我试图将它们保存到单独的文件中,以便保存在应用程序存储中。存储是一个名为“存储”的文件夹。在存储内部,有一个“ fileList.txt ”文件,其中包含文件列表。
在pubspec.yaml我在资产中声明了这个文件夹,如下所示:
assets:
- storage/
我可以使用以下函数阅读它:
Future<String> readFileContent() async {
String response;
response =
await rootBundle.loadString('storage/fileList.txt');
return response;
}
为了保存文件,我使用了使用“ path_provider ”包的在线示例。但是,当我尝试使用以下函数保存下载的文件之一时,例如“ file4.dat ”,我遇到以下错误。我该如何解决这个问题?
saveFileLocally() async {
await _writeFile();
}
Future<Null> _writeFile() async {
await (await _getLocalFile()).writeAsString(vars.fileContents);
}
Future<File> _getLocalFile() async {
// get the path to the document directory.
String dir = (await PathProvider.getApplicationSupportDirectory()).path;
print('DIR :::: ' + dir);
return new File(
'$dir/storage/files/file' + vars.newFileID.toString() + '.dat');
}
错误是:
Unhandled Exception: FileSystemException: Cannot open file,
path = '/data/user/0/com.example.ferenova_flutter_app/files/storage/file4.dat'
(OS Error: No such file or directory, errno = 2)
谢谢大家,保重!!!:)
解决方案
在查看path_provider
示例时,我遇到了这个重要的细节:
Directory directory = Platform.isAndroid
? await getExternalStorageDirectory() //FOR ANDROID
: await getApplicationSupportDirectory(); //FOR iOS
这解决了我的问题。我不再使用默认rootBundle
资产来处理任何外部文件。
推荐阅读
- android - 将值存储到服务类 FirebaseInstanceIDService 中的共享首选项
- angular - 如果一个网站不是有角度的,那么如何使用 protract?
- python - 如何使用 Selenium 和 Python 在 URL https://maps.mapmyindia.com/direction 中单击文本为“GET ROUTES”的元素?
- sql - 在合并查询中按月和年排序
- linux - 如何使用 curl 到 jira api 打印文本文件
- python - Django/React/WebGL 是一个糟糕的堆栈吗?
- javascript - 从输入类型文件javascript获取多个值
- node.js - rabbitMq 消息是否可以在一段时间后持久化?
- magento2 - 覆盖magento2中system.xml中的注释
- ios - 在 iOS 项目中使用 Google Identity-Aware Proxy 和 Google SignIn