首页 > 解决方案 > 将文件写入和读取移动设备

问题描述

我编写了以下代码,从 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++;
    });
  }

标签: flutterdart

解决方案


您的代码没有按照您认为的顺序运行,因此您最终会在文件写入之前尝试读取文件。如果您将我的答案用于您提出的其他问题,我认为您的代码会更容易理解:Reading data from url in List

再次,请阅读:https ://dart.dev/codelabs/async-await


推荐阅读