1

API page,我收集到我正在尝试做的事情没有功能。我想从将文本存储为字符串列表的文件中读取文本,操作文本并保存文件。第一部分很容易使用该功能:

abstract List<String> readAsLinesSync([Encoding encoding = Encoding.UTF_8])

但是,没有让我将列表的内容直接写入文件的功能,例如

abstract void writeAsLinesSync(List<String> contents, [Encoding encoding = Encoding.UTF_8, FileMode mode = FileMode.WRITE])

相反,我一直在使用:

abstract void writeAsStringSync(String contents, [Encoding encoding = Encoding.UTF_8, FileMode mode = FileMode.WRITE])

通过将列表减少为单个字符串。我确信我也可以使用 for 循环并逐行输入流。我想知道两件事:

  1. 有没有办法只把文件交给一个字符串列表来写?
  2. 为什么有 readAsLinesSync 但没有 writeAsLinesSync?这是疏忽还是设计决定?

谢谢

4

2 回答 2

3

我刚刚创建了自己的导出类来处理对文件的写入或将数据发送到 websocket。

用法:

exportToWeb(mapOrList, 'local', 8080);
exportToFile(mapOrList, 'local/data/data.txt');

班级:

//Save data to a file.
void exportToFile(var data, String filename) =>
    new _Export(data).toFile(filename);

//Send data to a websocket.
void exportToWeb(var data, String host, int port) =>
    new _Export(data).toWeb(host, port);

class _Export {

  HashMap mapData;
  List listData;
  bool isMap = false;
  bool isComplex = false;

  _Export(var data) {
    // Check is input is List of Map data structure.
    if (data.runtimeType == HashMap) {
      isMap = true;
      mapData = data;
    } else if (data.runtimeType == List) {
      listData = data;
      if (data.every((element) => element is Complex)) {
        isComplex = true;
      }
    } else {
      throw new ArgumentError("input data is not valid.");
    }
  }

  // Save to a file using an IOSink.  Handles Map, List and List<Complex>.   
  void toFile(String filename) {
    List<String> tokens = filename.split(new RegExp(r'\.(?=[^.]+$)'));
    if (tokens.length == 1) tokens.add('txt');
    if (isMap) {
      mapData.forEach((k, v) {
        File fileHandle = new File('${tokens[0]}_k$k.${tokens[1]}');
        IOSink dataFile = fileHandle.openWrite();
        for (var i = 0; i < mapData[k].length; i++) {
          dataFile.write('${mapData[k][i].real}\t'
              '${mapData[k][i].imag}\n');
        }
        dataFile.close();
      });
    } else {
      File fileHandle = new File('${tokens[0]}_data.${tokens[1]}');
      IOSink dataFile = fileHandle.openWrite();
      if (isComplex) {
        for (var i = 0; i < listData.length; i++) {
          listData[i] = listData[i].cround2;
          dataFile.write("${listData[i].real}\t${listData[i].imag}\n");
        }
      } else {
        for (var i = 0; i < listData.length; i++) {
          dataFile.write('${listData[i]}\n');
        }
      }
      dataFile.close();
    }
  }

  // Set up a websocket to send data to a client.
  void toWeb(String host, int port) {
    //connect with ws://localhost:8080/ws
    //for echo - http://www.websocket.org/echo.html
    if (host == 'local') host = '127.0.0.1';
    HttpServer.bind(host, port).then((server) {
      server.transform(new WebSocketTransformer()).listen((WebSocket webSocket) {
        webSocket.listen((message) {
          var msg = json.parse(message);
          print("Received the following message: \n"
                "${msg["request"]}\n${msg["date"]}");
            if (isMap) {
              webSocket.send(json.stringify(mapData));
            } else {
              if (isComplex) {
                List real = new List(listData.length);
                List imag = new List(listData.length);
                for (var i = 0; i < listData.length; i++) {
                  listData[i] = listData[i].cround2;
                  real[i] = listData[i].real;
                  imag[i] = listData[i].imag;
                }
                webSocket.send(json.stringify({"real": real, "imag": imag}));
              } else {
                webSocket.send(json.stringify({"real": listData, "imag": null}));
              }
            }
        },
        onDone: () {
            print('Connection closed by client: Status - ${webSocket.closeCode}'
                ' : Reason - ${webSocket.closeReason}');
            server.close();
        });
      });
    });
  }
}
于 2012-11-29T16:05:25.047 回答
2

我问过Mads Ages这件事。他在 io 模块上工作。他说他决定不添加 writeAsLines,因为他觉得它没有用。一方面,编写 for 循环很简单,另一方面,您必须将其参数化为您想要使用的行分隔符类型。他说,如果有强烈的感觉它很有价值,他可以添加它。他并没有立即看到其中的很多价值。

于 2012-11-29T14:17:27.173 回答