gpt4 book ai didi

dart - 如何在 Dart 中逐行读取文件

转载 作者:行者123 更新时间:2023-12-01 23:33:16 26 4
gpt4 key购买 nike

这个问题是 previous question 的延续.我写了下面一段代码来确定是否File.openRead()创建了一个可以逐行流式传输的 Stream。事实证明,答案是否定的。整个文件被读取,然后传递给下一个转换。我的问题是:如何在 Dart 中逐行流式传输文件?

import 'dart:async';
import 'dart:convert';
import 'dart:io';


void main(List<String> arguments) {

Stream<List<int>> stream = new File('Data.txt').openRead();

stream
.transform(const Utf8InterceptDecoder())
.transform(const LineSplitterIntercept())
.listen((line) {
// stdout.writeln(line);
}).asFuture().catchError((_) => print(_));
}

int lineSplitCount = 0;

class LineSplitterIntercept extends LineSplitter {

const LineSplitterIntercept() : super();
// Never gets called
List<String> convert(String data) {
stdout.writeln("LineSplitterIntercept.convert : Data:" + data);
return super.convert(data);
}

StringConversionSink startChunkedConversion(ChunkedConversionSink<String> sink) {
stdout.writeln("LineSplitterIntercept.startChunkedConversion Count:"+lineSplitCount.toString()+ " Sink: " + sink.toString());
lineSplitCount++;
return super.startChunkedConversion(sink);
}
}

int utfCount = 0;

class Utf8InterceptDecoder extends Utf8Decoder {

const Utf8InterceptDecoder() : super();

//never gets called
String convert(List<int> codeUnits) {
stdout.writeln("Utf8InterceptDecoder.convert : codeUnits.length:" + codeUnits.length.toString());
return super.convert(codeUnits);
}


ByteConversionSink startChunkedConversion(ChunkedConversionSink<String> sink) {
stdout.writeln("Utf8InterceptDecoder.startChunkedConversion Count:"+ utfCount.toString() + " Sink: "+ sink.toString());
utfCount++;
return super.startChunkedConversion(sink);
}
}

最佳答案

如果需要流,您可以从 readAsLines() 的 future 创建它返回:

   Stream<List<String>> stream = 
new Stream.fromFuture(new File('Data.txt').readAsLines());

然而,对我来说,简单地一一处理这些行看起来更简单,
  List<String> lines = new File('Data.txt').readAsLinesSync();
for (var line in lines) {
stdout.writeln(line);
}

关于dart - 如何在 Dart 中逐行读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20815913/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com