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资源来处理任何外部文件。

我认为您应该检查您的路径。

storage/fileList.txt与$dir/storage/files/file'+vars.loadedFileID.toString((+'.dat'不同

你应该试试:

response =
await rootBundle.loadString('$dir/storage/files/file' + vars.loadedFileID.toString() + '.dat'');

或者类似的东西
GL

相关内容

最新更新