问题描述
我正在开发一个从服务器收集文本内容的应用程序,下一步,我试图将它们保存到单独的文件中,以保存在应用程序存储中。存储是一个名为“存储”的文件夹。在存储内部,有一个' 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)
谢谢大家,保重!!! :)
解决方法
我认为您应该检查路径。
storage / fileList.txt与$ dir / storage / files / file'+ vars.loadedFileID.toString()+'.dat'
不同您应该尝试:
response =
await rootBundle.loadString('$dir/storage/files/file' + vars.loadedFileID.toString() + '.dat'');
或类似的东西。
GL
在查看path_provider
示例时,我遇到了以下重要细节:
Directory directory = Platform.isAndroid
? await getExternalStorageDirectory() //FOR ANDROID
: await getApplicationSupportDirectory(); //FOR iOS
这解决了我的问题。我不再使用默认的rootBundle
资产来处理任何外部文件。