flutter - 将文件写入和读取移动设备
问题描述
我编写了以下代码,从 URL 读取字符串,将内容写入文件,data.csv
然后尝试打开文件以读取其内容,csv
但出现错误:
I/flutter(6145):FileSystemException:无法打开文件,路径 = 'data.csv'(操作系统错误:没有这样的文件或目录,errno = 2) I/flutter(6145):文件现在已关闭。E/flutter(6145):[错误:flutter/lib/ui/ui_dart_state.cc(177)]未处理的异常:FileSystemException:无法打开文件,路径='data.csv'(操作系统错误:只读文件系统,errno = 30)
我的代码是:
import 'dart:convert';
import 'dart:io';
import 'dart:async';
void _incrementCounter() {
setState(() {
new HttpClient().getUrl(Uri.parse('https://docs.google.com/spreadsheets/d/e/2PACX-1vQvf9tp4-fETDJbC-HRmRKvVFAXEAGO4lrYPpVeiYkB6nqqXdSs3CjX0eBMvjIoEeX9_qU6K2RWmzVk/pub?gid=0&single=true&output=csv'))
.then((HttpClientRequest request) => request.close())
// .then((HttpClientResponse response) => response.transform(new Utf8Decoder()).listen(print));
.then((HttpClientResponse response) => response.pipe(new File('data.csv').openWrite()));
final File file = new File("data.csv");
Stream<List> inputStream = file.openRead();
inputStream
.transform(utf8.decoder) // Decode bytes to UTF-8.
.transform(new LineSplitter()) // Convert stream to individual lines.
.listen((String line) { // Process results.
List row = line.split(','); // split by comma
String city = row[0];
String branches = row[1];
print('$city, $branches');
},
onDone: () { print('File is now closed.'); },
onError: (e) { print(e.toString()); });
// List<List<dynamic>> rowsAsListOfValues = const CsvToListConverter().convert(yourString);
_counter++;
});
}
解决方案
您的代码没有按照您认为的顺序运行,因此您最终会在文件写入之前尝试读取文件。如果您将我的答案用于您提出的其他问题,我认为您的代码会更容易理解:Reading data from url in List
推荐阅读
- android - 如何在 RecyclerView 中获取项目的位置
- java - java中的局部变量访问
- javascript - 我想以特定方式转换对象数组
- javascript - 我不明白为什么计数器在一个按钮上起作用,而在另一个按钮上不起作用
- c# - 如何使用 Linq 通过嵌套列表的属性对对象列表进行排序?
- reactjs - 如何在静态 html 文件中使用 React ContextAPI
- graphics - 使用深度缓冲区进行光线行进
- php - 在特定页面中,运行函数来编辑标题
- react-native - 我正在尝试使用native-base,安装后出现此错误
- html - Flex 不为移动响应而包装